Here is a very good video explaining this algorithm:
https://www.youtube.com/watch?v=86CQq3pKSUw
1: class Solution {
2: public:
3: int maxProfit(vector<int>& prices) {
4: int maxGlobal = 0;
5: int maxCurrent = 0;
6: for (int i = 1; i < prices.size(); i++) {
7: maxCurrent = max(prices[i]-prices[i-1], maxCurrent + prices[i]-prices[i-1]);
8: if (maxCurrent > maxGlobal) maxGlobal = maxCurrent;
9: }
10: return maxGlobal;
11: }
12: };
No comments:
Post a Comment