#3742
Maximum Path Score in a Grid
MediumArrayDynamic ProgrammingMatrixDynamic ProgrammingGrid Traversal
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(2^(m+n)) | O(m * n * k) |
| Space | O(m+n) | O(m * n * k) |
💡
Intuition
Time O(m * n * k)Space O(m * n * k)
Use dynamic programming to store the maximum score at each cell for all possible costs. This avoids redundant calculations and efficiently finds the maximum score.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a 3D DP array where dp[i][j][c] represents the maximum score at cell (i, j) with cost c.
- 2Step 2: Fill the DP table by iterating through each cell and updating scores based on possible moves from the top or left cells.
- 3Step 3: Return the maximum score from the bottom-right cell for all costs up to k.
solution.py14 lines
1def maxPathScore(grid, k):
2 m, n = len(grid), len(grid[0])
3 dp = [[[-1] * (k + 1) for _ in range(n)] for _ in range(m)]
4 dp[0][0][0] = 0
5 for i in range(m):
6 for j in range(n):
7 for c in range(k + 1):
8 if dp[i][j][c] != -1:
9 score = grid[i][j]
10 cost = 1 if score > 0 else 0
11 for ni, nj in [(i + 1, j), (i, j + 1)]:
12 if ni < m and nj < n and c + cost <= k:
13 dp[ni][nj][c + cost] = max(dp[ni][nj][c + cost], dp[i][j][c] + score)
14 return max(dp[m - 1][n - 1]) if max(dp[m - 1][n - 1]) != -1 else -1ℹ
Complexity note: The complexity is driven by the need to fill a 3D DP table, iterating over all cells and possible costs.
- 1Dynamic programming reduces redundant calculations.
- 2Tracking costs alongside scores is essential.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.