买卖一次
1个变量记录目前已知最便宜,(当前 - 已知最便宜)= 当前最大收益
买卖无数次 https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii
特殊值的处理,如果全部一样的话,其实可以直接initiate peak && valley = prices[0], 这样对于总体的profit是没有变化的~
t1 < t2 < t3:
buy t1, sell t2 && buy t2 && t3 = buuy t1 && sell t2
这就是得到valley && peak方法的逻辑
profit = Sum (peak - valley)
最多两次
DP
分别用array来记录按照中间某个断点,左右分别可能的最大profit,有一种edge case是只需要一次交易,所以需要最后再多扫描一次
class Solution:
def maxProfit(self, prices: List[int]) -> int:
# Edge case
if prices is None or len(prices) <= 1:
return 0
# Divide && Counter
left_profits = [0] * len(prices)
left_profits[0] = 0
right_profits = [0] * len(prices)
right_profits[len(prices) - 1] = 0
# Populate left_profits
i = 1
low = prices[0]
profit = 0
while (i < len(prices)):
if prices[i] - low > profit:
profit = prices[i] - low
left_profits[i] = profit
# Update knwon low price
if prices[i] < low:
low = prices[i]
i = i + 1
# Populate right_profits
i = len(prices) - 2
hi = prices[i + 1]
profit = 0
while i >= 0:
if hi - prices[i] > profit:
profit = hi - prices[i]
right_profits[i] = profit
# Update known hi price
if prices[i] > hi:
hi = prices[i]
i = i - 1
# 3rd pass && get what is the overall best price
ret_profit = 0
# If has to conduct 2 transactions
for i in range(0, len(prices) - 1):
ret_profit = max(ret_profit, left_profits[i] + right_profits[i + 1])
# Edge case is it might just need 1 transaction
for i in range(0, len(prices)):
ret_profit = max(ret_profit, max(left_profits[i], right_profits[i]))
return ret_profit