Skip to content

Instantly share code, notes, and snippets.

@Ifihan
Created September 25, 2025 15:37
Show Gist options
  • Select an option

  • Save Ifihan/9894fffb4e274d9910b57656bfcba404 to your computer and use it in GitHub Desktop.

Select an option

Save Ifihan/9894fffb4e274d9910b57656bfcba404 to your computer and use it in GitHub Desktop.
Triangle

Question

Approach

I solve it with dynamic programming from the bottom up. I keep a 1D array dp representing the minimum path sums from the current row down to the bottom; I initialize dp to the last row of the triangle. Then I iterate upward row by row: for each element triangle[i][j] I update dp[j] = triangle[i][j] + min(dp[j], dp[j+1]). After processing the top row, dp[0] holds the answer.

Implementation

class Solution:
    def minimumTotal(self, triangle: List[List[int]]) -> int:
        if not triangle:
            return 0

        dp = triangle[-1][:]

        for i in range(len(triangle) - 2, -1, -1):
            row = triangle[i]
            for j in range(len(row)):
                dp[j] = row[j] + min(dp[j], dp[j + 1])

        return dp[0]

Complexities

  • Time: O(N)
  • Space: O(m)
image
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment