DEV Community

codingpineapple
codingpineapple

Posted on

3 2

LeetCode 64. Minimum Path Sum (javascript solution)

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.

Note: You can only move either down or right at any point in time.

Solution:

Time Complexity : O(n^2)
Space Complexity: O(n^2)

var minPathSum = function(grid) {
    // Create table
    const dp = new Array(grid.length).fill(0).map(() => Array(grid[0].length).fill(Infinity));
    // Add starting value
    dp[0][0] = grid[0][0]
    // Populate table
    for (let i = 0; i < dp.length; i++) {
        for(let j = 0; j < dp[0].length; j++) {
            // Add current cell total to cells to the right and below if the current cell + grid value of cell right/below is less than that cell's current total
            if(i+1 < dp.length) dp[i+1][j] = Math.min(dp[i+1][j], dp[i][j]+grid[i+1][j])
            if(j+1 < dp[0].length) dp[i][j+1] = Math.min(dp[i][j+1], dp[i][j]+grid[i][j+1])
        }
    }
    return dp[dp.length-1][dp[0].length-1]
};
Enter fullscreen mode Exit fullscreen mode

Heroku

Amplify your impact where it matters most — building exceptional apps.

Leave the infrastructure headaches to us, while you focus on pushing boundaries, realizing your vision, and making a lasting impression on your users.

Get Started

Top comments (0)

Neon image

Next.js applications: Set up a Neon project in seconds

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Get started →

👋 Kindness is contagious

Dive into this thoughtful article, cherished within the supportive DEV Community. Coders of every background are encouraged to share and grow our collective expertise.

A genuine "thank you" can brighten someone’s day—drop your appreciation in the comments below!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found value here? A quick thank you to the author makes a big difference.

Okay