Complete the code to find the maximum profit from a single buy and sell.
def max_profit(prices): min_price = float('inf') max_profit = 0 for price in prices: if price < [1]: min_price = price elif price - min_price > max_profit: max_profit = price - min_price return max_profit
We update the minimum price seen so far to find the best buying price.
Complete the code to calculate max profit with unlimited transactions.
def max_profit_unlimited(prices): profit = 0 for i in range(1, len(prices)): if prices[i] > [1]: profit += prices[i] - prices[i-1] return profit
We add profit only when today's price is higher than yesterday's.
Fix the error in the code to find max profit with at most two transactions.
def max_profit_two_transactions(prices): n = len(prices) left_profits = [0] * n right_profits = [0] * n min_price = prices[0] for i in range(1, n): min_price = min(min_price, prices[i]) left_profits[i] = max(left_profits[i-1], prices[i] - [1]) max_price = prices[-1] for i in range(n-2, -1, -1): max_price = max(max_price, prices[i]) right_profits[i] = max(right_profits[i+1], max_price - prices[i]) max_profit = 0 for i in range(n): max_profit = max(max_profit, left_profits[i] + right_profits[i]) return max_profit
We subtract the minimum price seen so far to calculate profit for the left side.
Fill both blanks to implement max profit with cooldown period.
def max_profit_cooldown(prices): n = len(prices) if n <= 1: return 0 sell = [0] * n buy = [0] * n buy[0] = -prices[0] for i in range(1, n): buy[i] = max(buy[i-1], sell[i-2] - [1]) if i > 1 else max(buy[i-1], -prices[i]) sell[i] = max(sell[i-1], buy[i-1] + [2]) return sell[-1]
We buy by subtracting current price and sell by adding current price.
Fill all three blanks to implement max profit with at most k transactions.
def max_profit_k_transactions(k, prices): if not prices or k == 0: return 0 n = len(prices) if k >= n // 2: profit = 0 for i in range(1, n): profit += max(0, prices[i] - prices[i-1]) return profit dp = [[0] * n for _ in range(k+1)] for i in range(1, k+1): max_diff = -prices[0] for j in range(1, n): dp[i][j] = max(dp[i][j-1], prices[j] + [1]) max_diff = max(max_diff, dp[i-1][j] - [2]) return dp[k][n-1]
We use max_diff to track the best previous state and update it with prices[j].
