Leetcode-Easy 121. Best Time to Buy and Sell Stock

96
致Great
2018.04.01 13:38 字数 119

121. Best Time to Buy and Sell Stock

  • 描述:
  • 思路:

[1,2,3,4] ==> returns 3 (buy at 1 and sell at 4)

[4,3,2,1] ==> returns 0 (don't buy)

[4,10,25,2,10] ==> returns 21 (buy at 4 and sell at 25)

遍历每天的价格,与当前最低价格相比较min_price;然后当前价格减去最低价格,算出当前利润profit;当前利润与最大利润相比较,得出结果。

  • 代码
class Solution:
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        max_profit, min_price = 0, float('inf')
        for price in prices:
            min_price=min(min_price,price)
            profit=price-min_price
            max_profit=max(max_profit,profit)
        return max_profit
数据结构算法
数据结构算法
1.4万字 · 8682阅读 · 128人关注
Web note ad 1