#1219
Path with Maximum Gold
MediumArrayBacktrackingMatrixBacktrackingRecursion
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(4^(m*n)) | O(m*n) |
| Space | O(m*n) | O(m*n) |
💡
Intuition
Time O(m*n)Space O(m*n)
The optimal solution also uses backtracking but leverages memoization to avoid recalculating results for already visited paths. This significantly reduces the number of recursive calls and improves performance.
⚙️
Algorithm
5 steps- 1Step 1: Initialize a variable to track the maximum gold collected.
- 2Step 2: For each cell in the grid, if it contains gold, start a backtracking search from that cell.
- 3Step 3: In the backtracking function, collect gold and mark the cell as visited.
- 4Step 4: Explore all four possible directions recursively, using memoization to store results of previously computed paths.
- 5Step 5: After exploring all paths from the current starting cell, backtrack by unmarking the cell as visited.
solution.py21 lines
1def getMaximumGold(grid):
2 def backtrack(x, y, visited):
3 if x < 0 or x >= len(grid) or y < 0 or y >= len(grid[0]) or (x, y) in visited or grid[x][y] == 0:
4 return 0
5 visited.add((x, y))
6 gold = grid[x][y]
7 max_gold = gold + max(
8 backtrack(x + 1, y, visited),
9 backtrack(x - 1, y, visited),
10 backtrack(x, y + 1, visited),
11 backtrack(x, y - 1, visited)
12 )
13 visited.remove((x, y))
14 return max_gold
15
16 max_gold = 0
17 for i in range(len(grid)):
18 for j in range(len(grid[0])):
19 if grid[i][j] > 0:
20 max_gold = max(max_gold, backtrack(i, j, set()))
21 return max_goldℹ
Complexity note: The time complexity is linear with respect to the number of cells because we visit each cell at most once during the backtracking process.
- 1Backtracking is essential for exploring all paths.
- 2Memoization can significantly improve performance.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.