Collect Gems in a Grid with Fatigue Penalty
Dynamic ProgrammingAuto-graded · 17 test casesLast updated
Tests grid-path DP with a carried state (fatigue level) that penalizes consecutive moves in the same direction, requiring careful state-space design and memoization.
Collect Gems in a Grid with Fatigue Penalty
You are a collector moving through a rectangular grid of cells. Each cell contains a non-negative integer representing the number of gems it holds. You start at the top-left cell (0, 0) and want to reach the bottom-right cell (rows-1, cols-1), collecting gems along the way.
Movement Rules
At each step you may move right or down only. However, your collector suffers from fatigue: if you make 2 or more consecutive moves in the same direction, every gem collected on that move (and every subsequent consecutive move in that direction) is halved (integer division by 2).
More precisely, define your streak as the number of consecutive moves you have just made in the same direction ending at the current cell (including the move that brought you here).
- If
streak == 1(you just changed direction, or this is your first move): collect gems at full value. - If
streak >= 2(you extended a run in the same direction): collect gems atgems // 2.
The gems in the starting cell (0,0) are always collected at full value (no move was made to get there).
Goal
Return the maximum total gems collectible on any valid path from (0, 0) to (rows-1, cols-1).
Constraints
1 <= rows, cols <= 500 <= grid[r][c] <= 1000gridis a list ofrowslists, each of lengthcols.- If
rows == 1andcols == 1, returngrid[0][0]. - A 1-row or 1-column grid is valid; you are forced to move in one direction the entire time (fatigue applies after the first move in that direction).
Examples
Example 1
Input: max_gems([[0, 3, 5], [1, 2, 3], [4, 0, 2]])
Output: 10
Example 2
Input: max_gems([[10]])
Output: 10
Example 3
Input: max_gems([[5, 1, 2, 8]])
Output: 11
Hints
Hint 1
Define your DP state as (row, col, last_direction, streak) where streak is capped at 2 since the penalty is the same for streak >= 2.
Hint 2
Use top-down memoization (or bottom-up) over the four-dimensional state space; the state space is at most 50 × 50 × 2 × 2 = 10 000 entries.
Hint 3
When you move to a new cell, compute the new streak: if the move direction equals last_direction, new_streak = min(streak + 1, 2); otherwise new_streak = 1. Then decide whether to apply full or halved gem value based on new_streak.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Key Insight
The fatigue penalty makes the naive "just track position" DP insufficient — two paths arriving at the same cell may differ in how many consecutive moves they've been making in the same direction, which affects both the gems collected at this cell and future gems. We must include this history in the state.
State Definition
dp(r, c, last_dir, streak)
(r, c)— current cell.last_dir— direction of the most recent move (0= right,1= down).streak— number of consecutive moves inlast_dirending here, capped at 2 (sincestreak = 3has exactly the same penalty and future consequences asstreak = 2).
Total states: 50 × 50 × 2 × 2 = 10,000 — easily feasible.
Gem Collection Rule
When entering cell (r, c) with the above state:
streak == 1→ full gems:grid[r][c]streak >= 2→ halved gems:grid[r][c] // 2
Transition
From state (r, c, last_dir, streak), for each next move direction d ∈ {right, down}:
new_streak = min(streak + 1, 2) if d == last_dir
= 1 otherwise
The answer for dp(r, c, last_dir, streak) is:
gems_here + max over valid moves of dp(next_r, next_c, d, new_streak)
Starting Cell
(0, 0) is always collected at full value (no move was made to get there). We handle it outside dp and simulate the two possible first moves with streak = 1.
Correctness
The state captures all information that affects future gem collection. The cap at streak = 2 is valid because the penalty function is identical for any streak ≥ 2 — there is no additional penalty beyond halving. The recurrence correctly propagates the maximum over all paths.
Complexity
- Time: O(rows × cols × 2 × 2) states × O(1) per state = O(rows × cols)
- Space: O(rows × cols) for the memoization cache plus O(rows + cols) recursion stack depth.
Reference Solution
from typing import List
from functools import lru_cache
def max_gems(grid: List[List[int]]) -> int:
rows = len(grid)
cols = len(grid[0])
@lru_cache(maxsize=None)
def dp(r, c, last_dir, streak):
if streak >= 2:
cell_gems = grid[r][c] // 2
else:
cell_gems = grid[r][c]
if r == rows - 1 and c == cols - 1:
return cell_gems
best = -1
# Move right
if c + 1 < cols:
new_dir = 0
new_streak = min(streak + 1, 2) if last_dir == 0 else 1
val = dp(r, c + 1, new_dir, new_streak)
if val > best:
best = val
# Move down
if r + 1 < rows:
new_dir = 1
new_streak = min(streak + 1, 2) if last_dir == 1 else 1
val = dp(r + 1, c, new_dir, new_streak)
if val > best:
best = val
return cell_gems + best
if rows == 1 and cols == 1:
return grid[0][0]
start_gems = grid[0][0]
best = -1
if cols > 1:
val = dp(0, 1, 0, 1)
if val > best:
best = val
if rows > 1:
val = dp(1, 0, 1, 1)
if val > best:
best = val
return start_gems + best