What is the optimal path to maximize collected rocks in a grid?

DSA
Hard
Goldman Sachs
123.8K views

This problem requires finding a path from the bottom-left to the top-right of a grid that maximizes a specific metric, typically involving dynamic programming.

Why Interviewers Ask This

This question tests a candidate's proficiency in dynamic programming, a critical skill for optimizing resource allocation and pathfinding problems in finance and tech. Interviewers want to see if the candidate can break down a complex problem into overlapping subproblems and define a clear state transition equation. It also evaluates their ability to reconstruct the actual path taken, not just the maximum value.

How to Answer This Question

Define the DP state clearly, such as dp[i][j] representing the maximum rocks collected to reach cell (i, j). Initialize the base cases for the first row and column. Iterate through the grid filling the DP table using the recurrence relation that takes the maximum of the possible previous moves (up or left). Finally, trace back from the destination to the start to reconstruct the optimal path, printing the sequence of coordinates.

Key Points to Cover

  • Define DP state as max value to reach current cell
  • Handle boundary conditions for first row and column
  • Use recurrence relation: current + max(up, left)
  • Backtrack to reconstruct the optimal path

Sample Answer

I would solve this using dynamic programming. I define a 2D array where dp[i][j] stores the maximum rocks collected to reach cell (i, j). I initialize the bottom-left corner with its own value and fill the first row and column by accumulating values since movement is restricted. For the rest of the grid, each cell's value is the current rock count plus the maximum of the cells directly below or to the left. After filling the table, the answer is in the top-right cell. To get the path, I backtrack from the top-right to the bottom-left, choosing the direction that yielded the maximum value at each step.

Common Mistakes to Avoid

  • Ignoring boundary conditions for the first row and column
  • Using recursion without memoization leading to exponential time
  • Failing to correctly reconstruct the path after computing values

Practice This Question with AI

Answer this question orally or via text and get instant AI-powered feedback on your response quality, structure, and delivery.

Start Practicing

Related Interview Questions

Browse all 35 DSA questionsBrowse all 13 Goldman Sachs questions