
[LeetCode] 122. Best Time to Buy and Sell Stock II

Check reachability backwards
idx as the current goal positionidx, move the goal to this index.In the end, if the goal reaches index 0, it means the start can reach the end → return True.
class Solution:
def maxProfit(self, prices: List[int]) -> int:
n = len(prices)
if n == 0:
return 0
opt = [0] * n
min_val = prices[0]
# opt[i] = max profit achievable up to day i
for i in range(1, n):
if prices[i] < min_val:
min_val = prices[i]
opt[i] = opt[i-1]
else:
opt[i] = max(opt[i-1], prices[i] - min_val)
return opt[n-1]
O(n) (single pass)O(1) (only one variable for profit)Track two states for each day
hold: maximum profit while holding a stockcash: maximum profit while not holding a stockTransitions:
hold = max(hold, cash - price) (buy or keep holding)cash = max(cash, hold + price) (sell or keep cash)class Solution:
def maxProfit(self, prices: List[int]) -> int:
if not prices:
return 0
hold = -prices[0]
cash = 0
for p in prices[1:]:
hold = max(hold, cash - p)
cash = max(cash, hold + p)
return cash
O(n)O(1) (two variables: hold and cash)