64. Minimum Path Sum
Asked at 15Microsoft54Amazon44Bloomberg40Google37Meta29Apple22Goldman Sachs70Infosys54Texas Instruments100General Motors60Waymo58Zoho52Nvidia48TikTok41Uber22
Problem
Moving only right or down, find the path from the top-left to the bottom-right of grid (non-negative numbers) with the smallest sum of cell values, and return that sum.
Example: [[1,3,1],[1,5,1],[4,2,1]] → 7 (1 → 3 → 1 → 1 → 1)
dp[r][c] = grid[r][c] + min(dp[r−1][c], dp[r][c−1]), with one row.
Complexity: O(m·n) time, O(n) space.
class Solution:
def minPathSum(self, grid: List[List[int]]) -> int:
n = len(grid[0])
row = [float("inf")] * n
row[0] = 0
for r in grid:
row[0] += r[0]
for c in range(1, n):
row[c] = r[c] + min(row[c], row[c - 1])
return row[-1]
assert Solution().minPathSum([[1, 3, 1], [1, 5, 1], [4, 2, 1]]) == 7
assert Solution().minPathSum([[1, 2, 3], [4, 5, 6]]) == 12
class Solution {
public int minPathSum(int[][] grid) {
int n = grid[0].length;
int[] row = new int[n];
Arrays.fill(row, Integer.MAX_VALUE);
row[0] = 0;
for (int[] r : grid) {
row[0] += r[0];
for (int c = 1; c < n; c++) row[c] = r[c] + Math.min(row[c], row[c - 1]);
}
return row[n - 1];
}
}
func minPathSum(grid [][]int) int {
n := len(grid[0])
row := make([]int, n) // cheapest path sum to each cell of the current row
for c := 1; c < n; c++ {
row[c] = math.MaxInt / 2 // nothing above the first row
}
for _, r := range grid {
row[0] += r[0]
for c := 1; c < n; c++ {
row[c] = r[c] + min(row[c], row[c-1])
}
}
return row[n-1]
}