Practice
Solution
Step 1: Understand problem constraints
At most two transactions means we must track states for 0, 1, or 2 completed transactions and whether we hold stock or not.Step 2: Identify suitable algorithm
Greedy and divide-and-conquer fail to consider overlapping subproblems and state transitions correctly. Brute force is correct but inefficient. DP with state machines efficiently tracks profits per transaction count and holding state.Final Answer:
Option A -> Option AQuick Check:
DP with states is standard for multi-transaction stock problems [OK]
- Assuming greedy picks always yield global optimum
- Using brute force without pruning
Solution
Step 1: Understand problem constraints
The problem requires maximizing sum without robbing adjacent houses, which is a classic overlapping subproblems scenario.Step 2: Identify suitable algorithm
Dynamic programming fits because it explores choices at each house (rob or skip) and uses previous results to build optimal solution.Final Answer:
Option A -> Option AQuick Check:
Greedy fails on cases like [2,7,9,3,1], DP finds max 12 [OK]
- Greedy approach fails on non-adjacent constraints
prev1 after the third iteration of the loop when input is [2, 1, 4]?
def rob(nums):
prev1, prev2 = 0, 0
for num in nums:
temp = prev1
prev1 = max(prev1, prev2 + num)
prev2 = temp
return prev1
Solution
Step 1: Trace iterations
Iteration 1 (num=2): prev1= max(0,0+2)=2, prev2=0 Iteration 2 (num=1): prev1= max(2,0+1)=2, prev2=2 Iteration 3 (num=4): prev1= max(2,2+4)=6, prev2=2Step 2: Identify value after third iteration
After third iteration, prev1=6Final Answer:
Option A -> Option AQuick Check:
Manual calculation confirms prev1=6 after third iteration [OK]
- Confusing prev1 and prev2 updates
- Off-by-one iteration counting
Solution
Step 1: Identify time complexity
The algorithm iterates once over the prices array, performing constant time operations per element -> O(n).Step 2: Identify space complexity
Only two variables (cash and hold) are maintained and updated each iteration -> O(1) space.Final Answer:
Option A -> Option AQuick Check:
Single pass and constant state variables confirm O(n) time and O(1) space [OK]
- Confusing recursion stack space with DP space
- Assuming DP table stored for all days
Solution
Step 1: Analyze recursion with memoization
Memoization caches results for each index i, so robFrom(i) is computed once per i.Step 2: Determine total calls and complexity
Since i ranges from 0 to n-1, total calls are O(n), each O(1) work -> O(n) time.Final Answer:
Option C -> Option CQuick Check:
Without memoization, calls explode exponentially; memoization reduces to linear [OK]
- Assuming recursion always exponential
- Ignoring memoization effect
