added solution & modified README.md for problem 121

This commit is contained in:
Hrishikesh S 2019-10-06 13:09:42 +05:30
parent f063b030f8
commit dffe9459dd
2 changed files with 29 additions and 1 deletions

View File

@ -23,6 +23,7 @@ LeetCode
|109|[Convert Sorted List to Binary Search Tree](https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/) | [C](./src/109.c)|Medium|
|110|[Balanced Binary Tree](https://leetcode.com/problems/balanced-binary-tree/) | [C](./src/110.c)|Easy|
|112|[Path Sum](https://leetcode.com/problems/path-sum/) | [C](./src/112.c)|Easy|
|121|[Best Time to Buy and Sell Stock](https://leetcode.com/problems/best-time-to-buy-and-sell-stock/) | [C](./src/121.c)|Easy|
|125|[Valid Palindrome](https://leetcode.com/problems/valid-palindrome/) | [C](./src/125.c)|Easy|
|136|[Single Number](https://leetcode.com/problems/single-number/) | [C](./src/136.c)|Easy|
|141|[Linked List Cycle](https://leetcode.com/problems/linked-list-cycle/) | [C](./src/141.c)|Easy|
@ -67,4 +68,4 @@ LeetCode
|938|[Range Sum of BST](https://leetcode.com/problems/range-sum-of-bst/) | [C](./src/938.c)|Easy|
|965|[Univalued Binary Tree](https://leetcode.com/problems/univalued-binary-tree/) | [C](./src/965.c)|Easy|
|977|[Squares of a Sorted Array](https://leetcode.com/problems/squares-of-a-sorted-array/) | [C](./src/977.c)|Easy|
|1189|[Maximum Number of Balloons](https://leetcode.com/problems/maximum-number-of-balloons/) | [C](./src/1189.c)|Easy|
|1189|[Maximum Number of Balloons](https://leetcode.com/problems/maximum-number-of-balloons/) | [C](./src/1189.c)|Easy|

27
leetcode/src/121.c Normal file
View File

@ -0,0 +1,27 @@
int maxProfit(int* prices, int pricesSize){
/* If there is only only one day, profit cannot be made
*/
if(pricesSize <= 1) {
return 0;
}
int min_element = prices[0];
int max_difference = prices[1] - min_element;
for(int i = 0; i < pricesSize; i++) {
/* whenever maximum profit can be made, we sell the stock.
so we change the maximum difference
*/
if(prices[i] - min_element > max_difference) {
max_difference = prices[i] - min_element;
}
/* if a cheaper stock is available, we make that the minimum element
*/
if(min_element > prices[i]) {
min_element = prices[i];
}
}
/* return 0 if max_difference is less than zero, incase there is no way of making profits
*/
return (max_difference < 0)? 0 : max_difference;
}