#1289
Minimum Falling Path Sum II
HardArrayDynamic ProgrammingMatrixDynamic ProgrammingMatrix Traversal
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n²) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n²)Space O(n)
The optimal solution uses dynamic programming to build the minimum falling path sum iteratively. It keeps track of the minimum sums for each row while ensuring that no two elements from adjacent rows are in the same column. This is like building a path down a staircase, where you remember the best way to get to each step.
⚙️
Algorithm
3 steps- 1Step 1: Create a DP array initialized to the first row of the grid.
- 2Step 2: For each subsequent row, calculate the minimum sum for each column while ensuring that the same column from the previous row is not chosen.
- 3Step 3: Return the minimum value from the last row of the DP array.
solution.py15 lines
1# Full working Python code
2
3def minFallingPathSum(grid):
4 n = len(grid)
5 dp = grid[0][:]
6 for i in range(1, n):
7 new_dp = [0] * n
8 for j in range(n):
9 min_val = float('inf')
10 for k in range(n):
11 if k != j:
12 min_val = min(min_val, dp[k])
13 new_dp[j] = grid[i][j] + min_val
14 dp = new_dp
15 return min(dp)ℹ
Complexity note: The time complexity is O(n²) because we iterate through each row and for each column, we check all other columns in the previous row. The space complexity is O(n) since we only keep track of the current and previous row sums.
- 1Dynamic programming is a powerful technique for optimization problems.
- 2Understanding how to track previous states can simplify complex problems.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.