Maximum Path Score in a Grid Problem
Description
LeetCode Problem 3742.
You are given an m x n grid where each cell contains one of the values 0, 1, or 2. You are also given an integer k.
You start from the top-left corner (0, 0) and want to reach the bottom-right corner (m - 1, n - 1) by moving only right or down.
Each cell contributes a specific score and incurs an associated cost, according to their cell values:
- 0: adds 0 to your score and costs 0.
- 1: adds 1 to your score and costs 1.
- 2: adds 2 to your score and costs 1.
Return the maximum score achievable without exceeding a total cost of k, or -1 if no valid path exists.
Note: If you reach the last cell but the total cost exceeds k, the path is invalid.
Example 1:
Input: grid = [[0, 1],[2, 0]], k = 1
Output: 2
Explanation:
The optimal path is:
Cell grid[i][j] Score Total Score Cost Total Cost
(0, 0) 0 0 0 0 0
(1, 0) 2 2 2 1 1
(1, 1) 0 0 2 0 1
Thus, the maximum possible score is 2.
Example 2:
Input: grid = [[0, 1],[1, 2]], k = 1
Output: -1
Explanation:
There is no path that reaches cell (1, 1) without exceeding cost k. Thus, the answer is -1.
Constraints:
1 <= m, n <= 2000 <= k <= 10^3grid[0][0] == 00 <= grid[i][j] <= 2
Solution
Approach: DP over cells and exact cost
Every cell with value 1 or 2 costs 1, so a path through m rows and n columns costs at most m + n - 2 (the start is 0). That means k can be capped at m + n - 2.
Let f[i][j][c] be the best score of a path from the top-left corner to (i, j) whose total cost is exactly c, or -1 if there is none. It comes from the cell above or the cell to the left with cost c - cost(i, j), plus the cell's value. Only the previous row is needed, so we keep one row of f. The answer is the largest value of f[m-1][n-1][c] over c <= k, which is -1 when no path fits.
Complexity: time O(m * n * min(k, m + n)), space O(n * min(k, m + n)).
class Solution:
def maxPathScore(self, grid: List[List[int]], k: int) -> int:
m, n = len(grid), len(grid[0])
k = min(k, m + n - 2) # a path never costs more than m + n - 2
# f[j][c]: best score at column j of the current row with total cost exactly c, -1 if impossible
f = [[-1] * (k + 1) for _ in range(n)]
for i in range(m):
for j in range(n):
v = grid[i][j]
cost = 1 if v else 0
cur = [-1] * (k + 1)
if i == 0 and j == 0:
cur[0] = 0
else:
up = f[j] if i > 0 else None
left = f[j - 1] if j > 0 else None
for c in range(cost, k + 1):
b = -1
if up is not None and up[c - cost] > b:
b = up[c - cost]
if left is not None and left[c - cost] > b:
b = left[c - cost]
if b >= 0:
cur[c] = b + v
f[j] = cur
return max(f[n - 1])