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

时间:2022-05-08
本文章向大家介绍Leetcode-Easy 121. Best Time to Buy and Sell Stock,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

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