~/problems / 2-D dynamic programming / Grid DP

Max-score grid path with limited jumps

hard 4 levels ~80 min OpenAI

Level 1 Best score to the bottom row

You get an n x m grid board of integers (possibly negative), a starting column p in the top row, and a jump budget k.

Start on (0, p). From (r, c) you may move to:

  • (r + 1, c - 1), (r + 1, c) or (r + 1, c + 1) (down-left, down, down-right), or
  • (r + 2, c): a jump straight down over one row. A path may use at most k jumps.

Every move must land inside the grid. The path ends when it reaches the last row (row n - 1). Its score is the sum of the values of every cell it visits (the start and the last cell included; a jumped-over cell is not visited).

Implement max_score(board, p, k) -> int.

board = [[0,  5,  0],
         [-9, -9, -9],
         [1,  4,  1]]
max_score(board, 1, 0)   # 0: 5 + (-9) + 4, every row-1 cell is -9
max_score(board, 1, 1)   # 9: jump (0,1) -> (2,1) skips the -9 row
max_score([[7, 1]], 0, 3)  # 7: a single row, you are already at the bottom

Constraints: 1 <= n <= 60, 1 <= m <= 40, 0 <= p < m, 0 <= k <= 8, -100 <= board[r][c] <= 100. Enumerating paths is exponential; aim for O(n·m·k).

Show hint

the best score from a cell depends on how many jumps you have left, not just on the cell. Make the jump count part of the state.

Level 2 unlocks when level 1 passes.

Level 3 unlocks when level 2 passes.

Level 4 unlocks when level 3 passes.

Topic: Grid DP. dp[r][c] from neighbours; add a dimension for extra state (jumps left).

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc