您的位置:首页 > 编程语言 > C语言/C++

Best Time to Buy and Sell Stock

2016-06-10 15:33 459 查看

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c语言