Skip to content

Path with Maximum Gold

MediumBacktracking
Decode it first. Clues, constraints, pattern and plan before any code.

A gold mine is a grid where grid[r][c] is the amount of gold in that cell (0 means empty). You collect gold by walking a path: start at any cell with gold, and each step moves up, down, left or right to another cell with gold. You may never visit a cell twice and never step onto an empty cell. Return the maximum gold you can collect.

[[0, 6, 0],
 [5, 8, 7],
 [0, 9, 0]]          →  24   (9 → 8 → 7)
 
[[1, 0, 7],
 [2, 0, 6],
 [3, 4, 5],
 [0, 3, 0],
 [9, 0, 20]]         →  28   (1 → 2 → 3 → 4 → 5 → 6 → 7)

Constraints

  • 1 <= rows, cols <= 15
  • 0 <= grid[r][c] <= 100
  • At most 25 cells contain gold.