121. Best Time to Buy and Sell Stock

题目链接: 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
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容