2. 分析
- 合理地改造原数据,这样会使得代码逻辑大大简化。
为了让代码走相同的逻辑,这里需要在原数据后面追加一个price = 0
。这个price = 0
大大地简化了处理[1,2,3,4,5]
这类型数据的复杂度。
3. 代码
class Solution:def maxProfit(self, prices: List[int]) -> int:max_profit = 0cost = 0stock_num = 0 prices.append(0)for i in range(len(prices)-1):cur_price = prices[i]next_price = prices[i+1]if cur_price < next_price and stock_num == 0: cost = cur_pricestock_num += 1elif cur_price > next_price and stock_num != 0: max_profit += (cur_price - cost)stock_num -= 1print(max_profit)return max_profit