LeetCode 1289: Minimum Falling Path Sum II Solution

Master LeetCode problem 1289 (Minimum Falling Path Sum II), a hard challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

1289. Minimum Falling Path Sum II

Problem Explanation

Explanation

To solve this problem, we can use dynamic programming. We will iterate over each row of the grid and calculate the minimum falling path sum ending at each element. For each element, we consider all elements from the previous row but not in the same column, and choose the minimum sum. This way, we build up the minimum falling path sum for each element in the grid.

Algorithm:

  1. Initialize a dp array to store the minimum falling path sum ending at each element in the grid.
  2. Iterate over each row of the grid.
  3. For each element in the row, calculate the minimum falling path sum by considering all elements from the previous row but not in the same column.
  4. Update the dp array with the minimum sum for each element.
  5. The minimum falling path sum will be the minimum value in the last row of the dp array.

Time Complexity: O(n^2) where n is the size of the grid. Space Complexity: O(n) for storing the dp array.

Solution Code

class Solution {
    public int minFallingPathSum(int[][] grid) {
        int n = grid.length;
        int[][] dp = new int[n][n];
        
        for (int i = 0; i < n; i++) {
            dp[0][i] = grid[0][i];
        }
        
        for (int i = 1; i < n; i++) {
            int[] temp = Arrays.copyOf(dp[i - 1], n);
            Arrays.fill(dp[i], Integer.MAX_VALUE);
            
            for (int j = 0; j < n; j++) {
                for (int k = 0; k < n; k++) {
                    if (k != j) {
                        dp[i][j] = Math.min(dp[i][j], temp[k] + grid[i][j]);
                    }
                }
            }
        }
        
        return Arrays.stream(dp[n - 1]).min().getAsInt();
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1289 (Minimum Falling Path Sum II)?

This page provides optimized solutions for LeetCode problem 1289 (Minimum Falling Path Sum II) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1289 (Minimum Falling Path Sum II)?

The time complexity for LeetCode 1289 (Minimum Falling Path Sum II) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1289 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1289 in Java, C++, or Python.

Back to LeetCode Solutions