题目链接: https://leetcode.com/problems/best-time-to-buy-and-sell-stock/description/
此题比较简单,对第i天
max_profit[i] = max(max_profit[i-1], price[i] - min(price[:i]))
等号右边第一项是第i-1天的最大利润,第二项是如果卖出第i的股票可能产生的最大利润。
完整java code:
class Solution {
public int maxProfit(int[] prices) {
if (prices.length == 0){
return 0;
}
int res = 0;
int buy = prices[0];
for (int i=1; i<prices.length; i++){
int sell = prices[i];
res = Math.max(res, sell-buy);
buy = Math.min(sell, buy);
}
return res;
}
}
完整python code:
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
if not prices:
return 0
buy = prices[0]
profit = 0
for i in range(1, len(prices)):
profit = max(profit, prices[i] - buy)
buy = min(buy, prices[i])
return profit
网友评论