Leetcode # 122. Best Time to Buy and Sell Stock II
- 2021.12.28
- LeetCode
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/
Solution
Key Point
先買在低谷 (valley),再賣在高峰 (peak)
class Solution: def maxProfit(self, prices: List[int]) -> int: profit = 0 valley = prices[0] i = 1 while i < len(prices) - 1: # peak if prices[i] > valley and prices[i] > prices[i + 1]: profit += prices[i] - valley valley = prices[i + 1] i += 1 elif valley > prices[i]: valley = prices[i] i += 1 if prices[-1] > valley: profit += (prices[-1] - valley) return profit
Last Updated on 2023/08/16 by A1go