You get a triangle of integers, triangle, where row r holds r + 1 numbers. Walk from the single number at the top down to the bottom row, one row per move.
From position i of a row you may step to position i or position i + 1 of the row below. Return the smallest total you can collect along such a walk, counting every number you stand on.
Example 1
Input: triangle = [[3],[6,2],[5,1,8],[4,7,2,6]] Output: 8 Why: 3 → 2 → 1 → 2 adds up to 8
2 more examples and the constraints
Example 2
Input: triangle = [[-7]] Output: -7 Why: one row: the walk is just the top
Example 3
Input: triangle = [[1],[2,3]] Output: 3 Why: step from 1 to the cheaper 2
Constraints
- The triangle has between 1 and 200 rows
- The top row has one value; every row below has one more than its parent
- −10,000 ≤ triangle[r][i] ≤ 10,000
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Recursion with a memoO(n²)
- Bottom-up, one rowO(n²)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative memory for 200 rows | Verdict |
|---|---|---|---|
| Recursion with a memo | O(n²) | Passes; O(n²) memo and a deep stack | |
| Bottom-up, one row | O(n²) | Best; O(n) extra space |
n = number of rows. Both do the same n²/2 updates; the bar shows memory.
Edge cases to test
- One row. The answer is the single value, even if negative.
- Greedy trap. In
[[1],[2,3],[9,9,1]], taking the smaller 2 leads to 12; the right answer, through 3, is 5. - Negative values. A path can get cheaper as it goes, so never stop early.
- Largest sums. 200 rows of ±10,000 total at most 2,000,000 in size, well inside a 32-bit int.
Common mistakes
- Choosing the smaller of the two cells below at each step; greedy misses cheaper paths further down.
- Updating
dpright to left in the bottom-up loop, sodp[i + 1]is overwritten before it is read. - Going top-down and returning
dp[n − 1][0]instead of the minimum of the last row.
How to talk through it
- 1Clarify. From index i, can I go to i and i + 1 only? Can values be negative?
- 2Show why greedy fails. Give a small triangle where the locally cheaper step loses.
- 3Define the subproblem. The cheapest path from a cell down depends only on the two cells below it.
- 4Go bottom-up with one row. Fold row by row into
dp; the top cell ends up holding the answer. - 5Test out loud. Run one row, the greedy trap and an all-negative triangle before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?