LeetCode123 买卖股票的最佳时机 III(贪心)
最多可以完成两笔交易,即分两段做LeetCode121,处理前缀后缀之后,遍历每一个分段节点所带来的收益取最大
class Solution:
def maxProfit(self, prices: List[int]) -> int:
pre_gains, suf_gains, pre_min, suf_max, l = [0], [0], prices[0], prices[-1], len(prices)
cur_max = 0
for i in range(l):
pre_min = min(pre_min, prices[i])
cur_max = max(cur_max, prices[i] - pre_min)
pre_gains.append(cur_max)
cur_max = 0
for i in range(l - 1, -1, -1):
suf_max = max(suf_max, prices[i])
cur_max = max(cur_max, suf_max - prices[i])
suf_gains.append(cur_max)
ans = 0
for i in range(l + 1):
ans = max(ans, pre_gains[i] + suf_gains[l - i])
return ans