美文网首页
121. Best Time to Buy and Sell S

121. Best Time to Buy and Sell S

作者: 春草恨离 | 来源:发表于2018-04-19 03:23 被阅读0次

    题目链接: 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
    

    相关文章

      网友评论

          本文标题:121. Best Time to Buy and Sell S

          本文链接:https://www.haomeiwen.com/subject/qhjikftx.html