120. Triangle
Asked at 10Bloomberg44Amazon36Google34Microsoft32Meta31Upstart54Walmart Labs43Infosys39tcs27Oracle27
Problem
From the top of triangle, move down one row at a time to index i or i + 1 of the next row. Return the minimum path sum from top to bottom.
Example: [[2],[3,4],[6,5,7],[4,1,8,3]] → 11 (2 + 3 + 5 + 1)
Constraints: follow-up: O(n) extra space, n = number of rows.
Go bottom-up: best[c] = tri[r][c] + min(best[c], best[c+1]). The top cell ends up holding the answer, no edge cases.
2 2+9=11
3 4 3+6=9 4+6=10
6 5 7 6+1=7 5+1=6 7+3=10
4 1 8 3 4 1 8 3
Complexity: O(n²) time, O(n) space.
class Solution:
def minimumTotal(self, triangle: List[List[int]]) -> int:
best = triangle[-1][:]
for r in range(len(triangle) - 2, -1, -1):
for c in range(r + 1):
best[c] = triangle[r][c] + min(best[c], best[c + 1])
return best[0]
assert Solution().minimumTotal([[2], [3, 4], [6, 5, 7], [4, 1, 8, 3]]) == 11
assert Solution().minimumTotal([[-10]]) == -10
class Solution {
public int minimumTotal(List<List<Integer>> triangle) {
int n = triangle.size();
int[] best = new int[n + 1];
for (int r = n - 1; r >= 0; r--)
for (int c = 0; c <= r; c++) best[c] = triangle.get(r).get(c) + Math.min(best[c], best[c + 1]);
return best[0];
}
}
func minimumTotal(triangle [][]int) int {
best := append([]int(nil), triangle[len(triangle)-1]...) // bottom-up: best path from each cell
for r := len(triangle) - 2; r >= 0; r-- {
for c := 0; c <= r; c++ {
best[c] = triangle[r][c] + min(best[c], best[c+1])
}
}
return best[0]
}