Practice
Solution
Step 1: Understand the cooldown constraint
The cooldown day after selling prevents immediate rebuying, which breaks greedy local min/max approaches.Step 2: Recognize the need for state tracking
Dynamic programming with states (holding, cooldown, free) models the problem accurately and efficiently.Final Answer:
Option C -> Option CQuick Check:
Greedy fails on cooldown; DP state machine handles it correctly [OK]
- Assuming greedy local min/max works despite cooldown
- Ignoring cooldown day after selling
Solution
Step 1: Understand circular adjacency constraint
The first and last houses cannot both be robbed, so the problem is not a simple linear DP.Step 2: Split into two linear problems
By considering two cases--rob houses from first to second last, or from second to last--we reduce the circular problem to two linear House Robber problems solvable by DP.Final Answer:
Option B -> Option BQuick Check:
Splitting into two linear DP subproblems handles circular adjacency correctly [OK]
- Assuming greedy or sorting works
- Trying to rob first and last house together
- Using brute force without pruning
curr during the first iteration of the loop when cost = [10, 15, 20]?Solution
Step 1: Initialize variables
prev2 = cost[0] = 10, prev1 = cost[1] = 15Step 2: Calculate curr at i=2
curr = cost[2] + min(prev1, prev2) = 20 + min(15, 10) = 20 + 10 = 30Final Answer:
Option A -> Option AQuick Check:
curr is sum of current cost plus min of previous two costs [OK]
- Mixing prev1 and prev2 values
- Off-by-one errors in loop
- Returning intermediate curr instead of final min
def maxProfit(prices, fee):
cash, hold = 0, -prices[0]
for price in prices[1:]:
cash = max(cash, hold + price) # Bug here: fee not subtracted
hold = max(hold, cash - price)
return cashWhat is the bug in this code?Solution
Step 1: Identify where fee is applied
The fee must be subtracted when selling stock, i.e., when updating cash.Step 2: Locate bug in code
cash update line adds hold + price but misses subtracting fee, leading to inflated profit.Final Answer:
Option C -> Option CQuick Check:
Missing fee subtraction causes incorrect profit calculation [OK]
- Forgetting fee on sell
- Incorrect initial hold value
Solution
Step 1: Understand the reuse variant
Reusing stock within a transaction means multiple buys/sells without reducing transaction count on buys.Step 2: Modify DP state transitions
Allow buy state updates without decrementing transactions_left, so holding state can be refreshed multiple times per transaction.Step 3: Why other options fail
Unlimited transactions shortcut ignores transaction limit; skipping buy updates breaks profit calculation; greedy fails with transaction constraints.Final Answer:
Option A -> Option AQuick Check:
Correct DP modification respects transaction count and allows multiple buys per transaction [OK]
- Using unlimited transactions shortcut incorrectly
- Skipping buy updates breaks DP correctness
