KatInterview

Collect Gems in a Grid with Fatigue Penalty

Dynamic ProgrammingAuto-graded · 17 test cases
MediumAuto-gradedDynamic Programmingdynamic programminggridmemoization

Last 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 at gems // 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 <= 50
  • 0 <= grid[r][c] <= 1000
  • grid is a list of rows lists, each of length cols.
  • If rows == 1 and cols == 1, return grid[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.