You are given an m x n integer matrix grid in which grid[i][j] is the number of coins in cell (i, j).
You start at the top-left corner (0, 0) and want to reach the bottom-right corner (m - 1, n - 1). From any cell you may move only right or down to an adjacent cell. As you pass through a cell, you collect all the coins in it.
Return the maximum number of coins you can collect on a single path from the start to the end.
Function Signature
def max_coins(grid: list[list[int]]) -> int:
Rules
-
grid
is a list of
m
rows, each a list of
n
integers.
-
A move goes from
(i, j)
to
(i, j + 1)
or to
(i + 1, j)
and must stay inside the grid.
-
The coins in the starting cell
(0, 0)
and in the ending cell
(m - 1, n - 1)
both count toward the total.
Constraints
-
1 <= m, n <= 100
-
0 <= grid[i][j] <= 1000
Examples
Input: grid = [[1,3,1],[1,5,1],[4,2,1]]
Output: 12
The path 1 -> 3 -> 5 -> 2 -> 1 (right, down, down, right) collects 12 coins. The other five right/down paths collect 7, 11, 9, 10 and 9 coins.
Input: grid = [[1,2,3],[4,5,6]]
Output: 16
The path 1 -> 4 -> 5 -> 6 (down, right, right) collects 16 coins. The two paths that start by moving right collect 14 and 12.
Input: grid = [[1,5,0],[2,1,0],[9,1,1]]
Output: 14
The path 1 -> 2 -> 9 -> 1 -> 1 (down, down, right, right) collects 14 coins. Every path through the 5 in the first row collects at most 9.