122. 买卖股票的最佳时机 II

  1. 题目链接

  2. 解题思路:来到i天,如果i的价格大于i-1的价格,那么就可以赚到差价。所以,遍历的过程中,只要prices[i] > prices[i - 1],那么就可以获利了

  3. 代码

    class Solution:
        def maxProfit(self, prices: List[int]) -> int:
            ans = 0
            for i in range(1, len(prices)):
                ans += max(0, prices[i] - prices[i - 1])
            return ans
    
  4. python更「简洁」的写法

    class Solution:
        def maxProfit(self, prices: List[int]) -> int:
            return sum(max(0, prices[i] - prices[i - 1]) for i in range(1, len(prices)))
    
posted @ 2024-12-26 15:12  ouyangxx  阅读(11)  评论(0)    收藏  举报