SDE & MLE Prep

120. Triangle

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]