2019-10-06 15:39:42 +08:00
|
|
|
int maxProfit(int* prices, int pricesSize){
|
|
|
|
/* If there is only only one day, profit cannot be made
|
|
|
|
*/
|
|
|
|
if(pricesSize <= 1) {
|
2019-10-06 15:51:53 +08:00
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
int min_element = prices[0];
|
|
|
|
int max_difference = prices[1] - min_element;
|
|
|
|
for(int i = 0; i < pricesSize; i++) {
|
2019-10-06 15:39:42 +08:00
|
|
|
/* whenever maximum profit can be made, we sell the stock.
|
2019-10-06 15:51:53 +08:00
|
|
|
* so we have to change to the new higher difference
|
2019-10-06 15:39:42 +08:00
|
|
|
*/
|
2019-10-06 15:51:53 +08:00
|
|
|
if(prices[i] - min_element > max_difference) {
|
|
|
|
max_difference = prices[i] - min_element;
|
2019-10-06 15:39:42 +08:00
|
|
|
}
|
|
|
|
/* if a cheaper stock is available, we make that the minimum element
|
|
|
|
*/
|
2019-10-06 15:51:53 +08:00
|
|
|
if(min_element > prices[i]) {
|
|
|
|
min_element = prices[i];
|
2019-10-06 15:39:42 +08:00
|
|
|
}
|
2019-10-06 15:51:53 +08:00
|
|
|
}
|
2019-10-06 15:39:42 +08:00
|
|
|
/* return 0 if max_difference is less than zero, incase there is no way of making profits
|
|
|
|
*/
|
2019-10-06 15:51:53 +08:00
|
|
|
return (max_difference < 0)? 0 : max_difference;
|
2019-10-06 15:39:42 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|