c++
class Solution {
public:
int maxProfit(vector<int>& prices) {
if (prices.empty())
return 0;
int profit_with_this_ending = 0;
int profit_so_far = 0;
for (int i = 1; i < prices.size(); ++i) {
profit_with_this_ending = max(0, profit_with_this_ending + (prices[i] - prices[i - 1]));
profit_so_far = max(profit_so_far, profit_with_this_ending);
}
return profit_so_far;
}
};
python
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
if len(prices) < 2:
return 0
profit_with_this_ending = 0
profit_so_far = 0
for i in xrange(1,len(prices),1):
profit_with_this_ending = max(0, profit_with_this_ending + prices[i]- prices[i-1])
profit_so_far = max(profit_with_this_ending, profit_so_far)
return profit_so_far
reference:
https://leetcode.com/discuss/48378/kadanes-algorithm-since-mentioned-about-interviewer-twists
https://en.wikipedia.org/wiki/Maximum_subarray_problem