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