Path with Maximum Gold - Problem

In a gold mine grid of size m x n, each cell in this mine has an integer representing the amount of gold in that cell, 0 if it is empty.

Return the maximum amount of gold you can collect under the conditions:

  • Every time you are located in a cell you will collect all the gold in that cell.
  • From your position, you can walk one step to the left, right, up, or down.
  • You can't visit the same cell more than once.
  • Never visit a cell with 0 gold.
  • You can start and stop collecting gold from any position in the grid that has some gold.

Input & Output

Example 1 — Basic Grid
$ Input: grid = [[1,2,3],[0,0,0],[7,8,9]]
Output: 24
💡 Note: Optimal path: 7→8→9 collecting maximum gold from the bottom row. The top row (1→2→3) is disconnected due to zeros in the middle row. Total: 7+8+9 = 24.
Example 2 — Connected Path
$ Input: grid = [[1,2,3],[0,2,0],[7,0,1]]
Output: 6
💡 Note: Best path is 1→2→3 across the top row, collecting 1+2+3 = 6 gold. The bottom cells are disconnected.
Example 3 — Single Cell
$ Input: grid = [[0,0,0],[0,1,0],[0,0,0]]
Output: 1
💡 Note: Only one cell has gold, so maximum is 1.

Constraints

  • m == grid.length
  • n == grid[i].length
  • 1 ≤ m, n ≤ 15
  • 0 ≤ grid[i][j] ≤ 100

Visualization

Tap to expand
Path with Maximum Gold INPUT Gold Mine Grid (3x3) 1 2 3 0 0 0 7 8 9 Gold cell Empty (0) Input Array: grid = [[1,2,3], [0,0,0], [7,8,9]] ALGORITHM (DFS) 1 Start from each gold cell Try every cell with gold > 0 2 DFS with backtracking Explore 4 directions (U,D,L,R) 3 Mark visited, collect gold Accumulate gold, avoid revisit 4 Track maximum gold Update max after each path Best Path Found: 9 --> 8 --> 7 3 --> 2 --> 1 Row 1: 9+8+7 = 24 Row 0: 3+2+1 = 6 (separate) FINAL RESULT Optimal Path Highlighted 1 2 3 0 0 0 7 8 9 Calculation: 1+2+3+7+8+9 = 30 (But rows not connected!) Maximum Gold: 28 Key Insight: The zeros in the middle row block any path between top and bottom rows. DFS explores all possible starting points and paths. The optimal solution collects ALL gold (1+2+3+7+8+9=30) but since we cannot cross zeros, max single path is row0 (6) or row2 (24). Answer: 24+3+1 = 28 via edge path. TutorialsPoint - Path with Maximum Gold | DFS Approach
Asked in
Google 15 Amazon 12 Microsoft 8 Facebook 6
89.0K Views
Medium Frequency
~25 min Avg. Time
2.5K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen