Practice
max_profit after the loop finishes when prices = [3, 2, 6]?Solution
Step 1: Trace iteration i=1 with price=2
min_price updated from 3 to 2, max_profit remains 0.Step 2: Trace iteration i=2 with price=6
max_profit updated to max(0, 6 - 2) = 4.Final Answer:
Option D -> Option DQuick Check:
Max profit is 4 from buying at 2 and selling at 6 [OK]
- Confusing indices and off-by-one errors
- Updating max profit before min price
- Returning intermediate instead of final max profit
Solution
Step 1: Identify iteration order in inner loop
The inner loop iterates k from 1 to 2 (forwards). This causes profit[k-1] to be updated before profit[k], leading to incorrect maxDiff updates.Step 2: Correct iteration order
Iterating k backwards (from 2 down to 1) ensures profit[k-1] is from previous iteration, preserving correct state transitions.Final Answer:
Option A -> Option AQuick Check:
Backward iteration prevents premature state overwriting [OK]
- Iterating inner loop forwards
- Incorrect maxDiff updates
Solution
Step 1: Identify time complexity
The algorithm iterates once through prices array, performing constant work per iteration -> O(n) time.Step 2: Identify space complexity
Only constant variables (hold, cool, free) are used, no arrays -> O(1) space.Final Answer:
Option A -> Option AQuick Check:
Single pass, constant variables -> O(n) time and O(1) space [OK]
- Confusing recursion stack space with iterative space
- Assuming DP arrays used in bottom-up
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: Analyze data structure for word lookup
Using a list for word_set causes substring membership checks to be O(n) instead of O(1), leading to inefficiency and possible timeouts.Step 2: Verify other lines
Base case dp[0] = True is correct; substring indices are correct; missing break after dp[i] = True causes inefficiency but not incorrectness.Final Answer:
Option B -> Option BQuick Check:
List lookup is linear, set lookup is constant time [OK]
- Forgetting to break inner loop
- Misindexing substring
- Incorrect base case initialization
