Practice
grid = [
[0, 1, -1],
[1, 0, -1],
[1, 1, 1]
]
from typing import List
def cherryPickup(grid: List[List[int]]) -> int:
n = len(grid)
dp = [[[-float('inf')] * n for _ in range(n)] for __ in range(n)]
dp[0][0][0] = grid[0][0]
for step in range(1, 2 * (n - 1) + 1):
for r1 in range(max(0, step - (n - 1)), min(n, step + 1)):
c1 = step - r1
if c1 < 0 or c1 >= n:
continue
for r2 in range(max(0, step - (n - 1)), min(n, step + 1)):
c2 = step - r2
if c2 < 0 or c2 >= n:
continue
if grid[r1][c1] == -1 or grid[r2][c2] == -1:
continue
candidates = []
if r1 > 0 and r2 > 0:
candidates.append(dp[r1 - 1][c1][r2 - 1])
if r1 > 0 and c2 > 0:
candidates.append(dp[r1 - 1][c1][r2])
if c1 > 0 and r2 > 0:
candidates.append(dp[r1][c1 - 1][r2 - 1])
if c1 > 0 and c2 > 0:
candidates.append(dp[r1][c1 - 1][r2])
best_prev = max(candidates) if candidates else -float('inf')
if best_prev == -float('inf'):
continue
val = best_prev + grid[r1][c1]
if r1 != r2:
val += grid[r2][c2]
dp[r1][c1][r2] = max(dp[r1][c1][r2], val)
return max(0, dp[n - 1][n - 1][n - 1])
print(cherryPickup(grid))
Solution
Step 1: Trace dp states for step=4 (final step for 3x3 grid)
At step=4, both players reach bottom-right (2,2). The dp value dp[2][2][2] accumulates max cherries collected along valid paths avoiding thorns (-1).Step 2: Calculate max cherries collected
By tracing paths, max cherries collected is 6, considering both players' paths and avoiding double counting.Final Answer:
Option A -> Option AQuick Check:
Manual path tracing confirms max cherries = 6 [OK]
- Off-by-one errors in step or indices
- Double counting cherries when players overlap
- Ignoring thorn cells leading to invalid paths
Solution
Step 1: Understand problem constraints
The problem requires minimum initial health ensuring health never drops below 1, which depends on future cells, so greedy or shortest path won't work.Step 2: Identify correct DP direction
Starting from the bottom-right cell and moving backward allows computing minimum health needed at each cell based on future states.Final Answer:
Option A -> Option AQuick Check:
Backward DP correctly accounts for future health requirements [OK]
- Assuming greedy or forward DP works
- Using shortest path ignoring health constraints
def findCheapestPrice(n, flights, src, dst, K):
INF = float('inf')
prev = [INF] * n
prev[src] = 0
for _ in range(K + 1):
for u, v, w in flights:
if prev[u] != INF:
prev[v] = min(prev[v], prev[u] + w)
return prev[dst] if prev[dst] != INF else -1
Solution
Step 1: Understand the DP update mechanism
In bottom-up DP, updates for the current iteration must not affect other relaxations in the same iteration, so a separate curr array is needed.Step 2: Identify the bug
Using prev directly causes updated costs to be used immediately in the same iteration, leading to incorrect minimum costs.Final Answer:
Option C -> Option CQuick Check:
Separate curr array prevents premature updates [OK]
- Updating prev in-place during iteration
- Forgetting to copy arrays
- Ignoring stop constraints
def stoneGame(piles):
n = len(piles)
dp = [[0]*n for _ in range(n)]
for i in range(n):
dp[i][i] = piles[i]
for length in range(2, n+1):
for i in range(n - length + 1):
j = i + length - 1
dp[i][j] = max(piles[i] + dp[i+1][j], piles[j] + dp[i][j-1])
return dp[0][n-1] > 0
Solution
Step 1: Understand dp state meaning
dp[i][j] should represent the maximum difference in stones the current player can achieve over the opponent.Step 2: Identify incorrect recurrence
The buggy line adds piles[i] + dp[i+1][j], which ignores the opponent's optimal response. The correct formula subtracts dp[i+1][j] to account for opponent's best play.Final Answer:
Option A -> Option AQuick Check:
Correct recurrence uses subtraction, not addition [OK]
- Adding dp values instead of subtracting opponent's score
- Forgetting base case initialization
Solution
Step 1: Understand constraint relaxation
Allowing same color for adjacent houses removes the need to exclude previous color in DP transitions.Step 2: Modify DP accordingly
Now min_prev is simply min(dp) over all colors, no exclusion needed. This simplifies the DP and still finds minimum cost.Step 3: Evaluate other options
Adding penalty is unnecessary. Brute force is inefficient. Greedy fails because costs vary per house and color.Final Answer:
Option C -> Option CQuick Check:
Relaxed constraints allow including all colors in min calculation [OK]
- Still excluding previous color unnecessarily
- Adding penalty complicates solution
- Using brute force or greedy incorrectly
