Triangle - Problem
Triangle Path Sum Challenge
Imagine you're standing at the top of a mountain represented as a triangular array of numbers. Your goal is to find the minimum cost path from the summit to the base.
๐ฏ The Rules:
โข Start at the top of the triangle (index 0)
โข At each step, you can only move to
โข From position
โข Find the path with the minimum sum of all numbers encountered
Example: Given triangle
Imagine you're standing at the top of a mountain represented as a triangular array of numbers. Your goal is to find the minimum cost path from the summit to the base.
๐ฏ The Rules:
โข Start at the top of the triangle (index 0)
โข At each step, you can only move to
adjacent positions in the row belowโข From position
i, you can move to either position i or i + 1 in the next rowโข Find the path with the minimum sum of all numbers encountered
Example: Given triangle
[[2],[3,4],[6,5,7],[4,1,8,3]], the minimum path is 2 โ 3 โ 5 โ 1 = 11 Input & Output
example_1.py โ Basic Triangle
$
Input:
triangle = [[2],[3,4],[6,5,7],[4,1,8,3]]
โบ
Output:
11
๐ก Note:
The minimum path is 2 โ 3 โ 5 โ 1 with sum = 11. At each level, we choose the adjacent position that leads to the minimum total.
example_2.py โ Single Element
$
Input:
triangle = [[-10]]
โบ
Output:
-10
๐ก Note:
With only one element, the minimum (and only) path sum is the element itself: -10.
example_3.py โ Two Rows
$
Input:
triangle = [[1],[2,3]]
โบ
Output:
3
๐ก Note:
Two possible paths: 1โ2 (sum=3) and 1โ3 (sum=4). The minimum is 3.
Constraints
- 1 โค triangle.length โค 200
- -104 โค triangle[i][j] โค 104
- Triangle property: triangle[i] has exactly i+1 elements
Visualization
Tap to expand
Understanding the Visualization
1
Survey the Base
Start at the bottom row - these are our base cases with known costs
2
Work Upward
For each position, choose the minimum cost path from the two adjacent positions below
3
Optimal Substructure
Each position now stores the minimum cost to reach the bottom from that point
4
Reach the Summit
The top position contains the minimum total path cost
Key Takeaway
๐ฏ Key Insight: Bottom-up DP ensures we always make optimal local decisions that lead to the global optimum!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code