Minimum Falling Path Sum II - Problem
Imagine you're a treasure hunter navigating through a dangerous multi-level dungeon! 🏴☠️ You have an
One valid path could be: pick 1 (row 0, col 0) → pick 5 (row 1, col 1) → pick 9 (row 2, col 2), giving sum = 15.
n x n grid where each cell contains a treasure value (which could be negative - representing traps!). Your goal is to collect treasures by moving from the top row to the bottom row, picking exactly one treasure from each level.
Here's the catch: you cannot pick treasures directly below each other - you must shift to a different column in each move. This is called a "falling path with non-zero shifts."
Your mission: Find the path that gives you the minimum sum of treasures collected.
Example: If you have a 3x3 grid:[[1,2,3], [4,5,6], [7,8,9]]One valid path could be: pick 1 (row 0, col 0) → pick 5 (row 1, col 1) → pick 9 (row 2, col 2), giving sum = 15.
Input & Output
example_1.py — Basic 3x3 Grid
$
Input:
grid = [[1,2,3],[4,5,6],[7,8,9]]
›
Output:
13
💡 Note:
The minimum falling path is [1,5,9] → but this violates the non-zero shift constraint. Valid paths include [1,4,8]=13, [1,6,7]=14, [2,4,9]=15, [2,6,7]=15, [3,4,8]=15, [3,5,7]=15. The minimum is 13.
example_2.py — Single Element
$
Input:
grid = [[7]]
›
Output:
7
💡 Note:
With only one element, there's no choice but to take that element. No shifts are needed since there's only one row.
example_3.py — Negative Values
$
Input:
grid = [[2,1,3],[6,5,4],[7,8,9]]
›
Output:
13
💡 Note:
Optimal path: [1,6,9] = 16? No, that's same column! Try [1,4,7] = 12? No, positions are [0,1], [2,2], [2,0] - invalid. Valid: [1,6,7]=14, [1,4,8]=13. Minimum is 13.
Constraints
- n == grid.length == grid[i].length
- 1 ≤ n ≤ 200
- -99 ≤ grid[i][j] ≤ 99
- Non-zero shifts required - cannot pick elements in same column from adjacent rows
Visualization
Tap to expand
Understanding the Visualization
1
Track Best Options
For each level, identify the minimum and second minimum treasure values
2
Smart Path Choice
When moving to next level, choose the best available option (avoiding same column)
3
Accumulate Optimally
Build up the best path by always making locally optimal choices
4
Final Treasure Count
The minimum value in the last row gives us the optimal treasure sum
Key Takeaway
🎯 Key Insight: By tracking only the minimum and second minimum values from each row, we can make optimal decisions in constant time per cell, achieving the best possible time complexity of O(n²) while using minimal space.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code