Collect the Most Rocks with Upward and Rightward Moves
Goldman SachsSoftware Engineer · OnsiteLast updated
Tests dynamic programming on a grid to find an optimal path from the bottom-left to top-right corner using constrained directional moves.
Collect the Most Rocks
You are given an m x n 2D integer array grid, where grid[r][c] represents the number of rocks present at coordinate (r, c).
You start at the bottom-left corner of the grid (m - 1, 0) and must reach the top-right corner (0, n - 1). At each step, you can only move:
- Up: from
(r, c)to(r - 1, c) - Right: from
(r, c)to(r, c + 1)
When you visit a cell, you collect all the rocks located in that cell. Return the maximum total number of rocks you can collect.
Function Signature
def max_rocks(grid: list[list[int]]) -> int:
pass
Examples
Example 1:
Input: grid = [
[0, 2, 5],
[1, 1, 3],
[2, 1, 1]
]
Output: 12
Explanation:
Start at (2, 0) with 2 rocks.
Move up to (1, 0) (+1 = 3).
Move right to (1, 1) (+1 = 4).
Move right to (1, 2) (+3 = 7).
Move up to (0, 2) (+5 = 12).
Total rocks collected = 12.
Example 2:
Input: grid = [
[1, 3],
[2, 4]
]
Output: 8
Explanation:
Path: (1, 0) -> (1, 1) -> (0, 1)
Rocks: 2 + 4 + 3 = 9
Path: (1, 0) -> (0, 0) -> (0, 1)
Rocks: 2 + 1 + 3 = 6
The maximum is 9.
Constraints
m == len(grid)n == len(grid[0])1 <= m, n <= 10000 <= grid[r][c] <= 10^5
Edge Cases
1 x 1grid: The answer is simplygrid[0][0].- Single row (
m = 1) or single column (n = 1): Only one valid path exists.
Hints
Hint 1
Identify the incoming directions: to reach cell (r, c), you must have arrived from either the cell below it (r + 1, c) or the cell to its left (r, c - 1).
Hint 2
Process the grid row-by-row starting from the bottom row (m - 1) up to the top row (0), updating the maximum rocks collectible up to each cell.
Hint 3
Notice that computing values for row r only depends on values from row r and row r + 1, which allows reducing auxiliary space to O(n).
Follow-up questions
- How would you reconstruct and return the exact path (list of coordinates) that yields the maximum rocks?
- If certain cells contain obstacles (e.g., value -1) that cannot be stepped on, how would you modify your solution to determine if the destination is reachable?
- How would you solve the problem if two collectors start at the bottom-left simultaneously and collect rocks without double-counting cells they both visit?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.