Given a triangle array of integers, return the minimum path sum from top to bottom.
For each step, you may move to an adjacent number of the row below. More formally, if you are on index i on the current row, you may move to either index i or index i + 1 on the next row.
Function Signature
def minimum_total(triangle: list[list[int]]) -> int:
Rules
-
The triangle is a list of rows. Row
r
holds
r + 1
integers.
-
A path starts at
triangle[0][0]
, takes exactly one value from every row, and ends in the bottom row.
-
Return the sum of the values on the cheapest path. Only the sum is returned, so the answer is unique even when several paths tie.
Constraints
-
1 <= len(triangle) <= 200
-
len(triangle[0]) == 1
-
len(triangle[i]) == len(triangle[i - 1]) + 1
-
-10^4 <= triangle[i][j] <= 10^4
Examples
Input: triangle = [[2], [3, 4], [6, 5, 7], [4, 1, 8, 3]]
Output: 11
2
/ \
3 4
/ \ / \
6 5 7
/ \ / \ / \
4 1 8 3
The minimum path is 2 -> 3 -> 5 -> 1, which sums to 11. Every other path costs at least 12.
Input: triangle = [[-10]]
Output: -10
The triangle has a single value, so the only path is that value.
Input: triangle = [[1], [2, 3], [9, 9, -10]]
Output: -6
Taking the smaller value 2 in the second row only reaches the two 9s, for a total of 12. The best path takes 3 so it can reach -10: 1 -> 3 -> -10 = -6.