forked from TheAlgorithms/C
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
adding Kandane's algorithm as the solution
- Loading branch information
1 parent
132c3c4
commit 6bcdac5
Showing
1 changed file
with
13 additions
and
23 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,27 +1,17 @@ | ||
int maxcmp(int a, int b) { | ||
return (a >= b)? a : b; | ||
} | ||
|
||
/* max subarray problem by using Kadane's Algorithm | ||
*/ | ||
int maxProfit(int* prices, int pricesSize){ | ||
/* If there is only only one day, profit cannot be made | ||
/* maxCur: current maximum | ||
* maxSoFar: found maximum for subarray so far | ||
*/ | ||
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 have to change to the new higher 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]; | ||
} | ||
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); | ||
} | ||
/* return 0 if max_difference is less than zero, incase there is no way of making profits | ||
*/ | ||
return (max_difference < 0)? 0 : max_difference; | ||
return maxSoFar; | ||
} | ||
|
||
|