2019-10-12 11:35:36 +08:00
|
|
|
int maxcmp(int a, int b) {
|
|
|
|
return (a >= b)? a : b;
|
|
|
|
}
|
|
|
|
|
|
|
|
/* max subarray problem by using Kadane's Algorithm
|
|
|
|
*/
|
2019-10-06 15:39:42 +08:00
|
|
|
int maxProfit(int* prices, int pricesSize){
|
2019-10-12 11:35:36 +08:00
|
|
|
/* maxCur: current maximum
|
|
|
|
* maxSoFar: found maximum for subarray so far
|
2019-10-06 15:39:42 +08:00
|
|
|
*/
|
2019-10-12 11:35:36 +08:00
|
|
|
int maxCur = 0, maxSoFar = 0;
|
|
|
|
for(int i = 1; i < pricesSize; i++) {
|
|
|
|
maxCur = maxcmp(0, maxCur + prices[i] - prices[i - 1]);
|
|
|
|
maxSoFar = maxcmp(maxSoFar, maxCur);
|
2019-10-06 15:51:53 +08:00
|
|
|
}
|
2019-10-12 11:35:36 +08:00
|
|
|
return maxSoFar;
|
2019-10-06 15:39:42 +08:00
|
|
|
}
|