Practice
Solution
Step 1: Trace profit and maxDiff arrays
Initialize profit=[0,0,0], maxDiff=[-1,-1,-1]. At i=1 (price=2): k=2: profit[2]=max(0,2-1)=1, maxDiff[2]=max(-1,0-2)=-1 k=1: profit[1]=max(0,2-1)=1, maxDiff[1]=max(-1,0-2)=-1 At i=2 (price=4): k=2: profit[2]=max(1,4-1)=3, maxDiff[2]=max(-1,1-4)=-1 k=1: profit[1]=max(1,4-1)=3, maxDiff[1]=max(-1,0-4)=-1Step 2: Final profit[2] value
After last iteration, profit[2] = 3.Final Answer:
Option D -> Option DQuick Check:
Profit matches max gain from two transactions [OK]
- Off-by-one in loop indices
- Confusing profit[k] with profit[k-1]
Solution
Step 1: Identify loops in the code
Outer loop runs n-1 times, inner loop runs k times (k=2 fixed). So total iterations ~ n*k.Step 2: Simplify complexity with fixed k
Since k=2 is constant, O(n*k) simplifies to O(n).Final Answer:
Option C -> Option CQuick Check:
Linear time due to fixed number of transactions [OK]
- Confusing k as variable leading to O(n*k)
- Assuming nested loops always mean O(n^2)
Solution
Step 1: Analyze time complexity
The algorithm iterates once over the price list (length n), performing constant time operations per iteration -> O(n) time.Step 2: Analyze space complexity
Only two variables track states (holding, not_holding), no arrays or recursion stack -> O(1) space.Final Answer:
Option B -> Option BQuick Check:
Single pass with constant state variables confirms O(n) time and O(1) space [OK]
- Confusing recursion stack space with iterative DP
- Assuming DP always uses O(n) space
- Mistaking nested loops for this linear solution
Solution
Step 1: Identify two-digit addition logic
The two-digit check should add prev2, not prev1, because it represents ways two steps back.Step 2: Understand impact on '0' handling
Adding prev1 instead of prev2 causes overcounting or invalid counts when '0' appears, e.g., '10' or '20'.Final Answer:
Option B -> Option BQuick Check:
Correct two-digit addition uses prev2, not prev1 [OK]
- Confusing prev1 and prev2 in two-digit addition
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
