Path with Maximum Gold

Medium · Backtracking · Array · Backtracking · Matrix · Depth-First Search

Problem

A gold mine is an m x n grid where each cell holds some amount of gold, and 0 means the cell is empty. Collect as much gold as you can under these rules:

Return the most gold a single walk can collect.

Examples

Input: grid = [[4,0,2],[3,1,5]]
Output: 15

The walk 4 → 3 → 1 → 5 → 2 visits every gold cell.

Input: grid = [[8,0],[0,1]]
Output: 8

The two gold cells only touch diagonally, so the best is the 8 alone.

Input: grid = [[0,6,0],[5,8,7],[0,9,0]]
Output: 24

Through the center a walk can use only two arms: 9 → 8 → 7 collects 24.

Constraints

Approaches

Follow-up

The search is exponential in the number of gold cells, which the limit of 25 keeps small. The use cases maximize the number of cells instead of the gold and fix the starting cell.

Related problems

Start free on Cariara · Coding problems · System design studio

Starting Python
No results yet.

          
↑↓ move ↵ open esc close

Labs

Loading labs…

Run with your own input

Starting Python

Loading Python…