DevPath

← All problems

Minimum Path Sum

Medium dynamic-programming · matrix

Description

Move only right or down from the top-left to the bottom-right. Return the minimum sum along a path.

Constraints

1 <= rows, cols <= 200; 0 <= cell

Examples

Input: grid = [[1,3,1],[1,5,1],[4,2,1]]

Output: 7

Hints (1)
  • Each cell is its value plus the smaller of the cell above and to the left.

Solutions

Rolling DP row. · Time O(rows*cols) · Space O(cols)

func minPathSum(grid [][]int) int {
    rows, cols := len(grid), len(grid[0])
    dp := append([]int{}, grid[0]...)
    for j := 1; j < cols; j++ {
        dp[j] += dp[j-1]
    }
    for i := 1; i < rows; i++ {
        dp[0] += grid[i][0]
        for j := 1; j < cols; j++ {
            best := dp[j]
            if dp[j-1] < best {
                best = dp[j-1]
            }
            dp[j] = grid[i][j] + best
        }
    }
    return dp[cols-1]
}

Create a free account to submit solutions, track progress and save problems.

Create account