Algorithm Day93 - Minimum Path Sum
🧩 Problem Description
Given a m x n grid filled with non-negative numbers, find a path from top-left to bottom-right, which minimizes the sum of all numbers along its path.
You can only move either down or right at any point in time.
💬 Examples
Example 1
1 | Input: grid = [[1,3,1],[1,5,1],[4,2,1]] |
Example 2
1 | Input: grid = [[1,2,3],[4,5,6]] |
💡 Intuition
This is a classic dynamic programming problem on a grid.
At each cell (i, j), the minimum path sum equals the cell value plus the smaller of the top or left neighbor:
1 | dp[i][j] = grid[i][j] + min(dp[i-1][j], dp[i][j-1]) |
We can compute this iteratively using either a 2D or 1D DP array.
🔢 Java Code (2D DP)
1 | class Solution { |
🔢 Java Code (1D DP Optimization)
1 | class Solution { |
⏱ Complexity Analysis
- Time: O(m × n)
- Space: O(n) (after optimization)
✍️ Summary
- Classic DP grid problem.
- Choose minimum between top and left cells.
- Can be optimized to 1D array.
Related problems:
lc-62(Unique Paths)lc-63(Unique Paths II)lc-120(Triangle)