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: 28
💡 Note: Optimal path: 7→8→9→3→2→1 collecting all gold cells. Total: 7+8+9+3+2+1 = 30. Wait, let me recalculate: We can collect 1+2+3 from top row = 6, or 7+8+9 from bottom = 24, but cannot connect them due to zeros. Best is 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 ProblemInput Grid123000789Explore Paths123Path 1: 1+2+3 = 6789Path 2: 7+8+9 = 24Maximum Path789Maximum: 24Algorithm: Try starting from each gold cell, use DFS to explore all pathsMark cells as visited during exploration, backtrack to try other pathsReturn the path with maximum total gold collected
Understanding the Visualization
1
Input Grid
Grid with gold amounts, 0 means empty cell
2
Find Paths
Explore all possible paths from each gold cell
3
Maximum Path
Return the path with maximum total gold
Key Takeaway
🎯 Key Insight: Must explore all possible starting positions using backtracking since optimal path can begin from any gold cell
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