Triangle

Dynamic Programming DP on grids Medium
  • This problem, also known as the 'Minimum Path Sum in a Triangle', has fundamental relevance in graph theory and network routing
  • It is used in practical cases such as network routing, where the goal is to find the path of least resistance (or in this case, the least sum)
  • This algorithm is essential for tasks such as Google Maps or other GPS navigation systems to calculate and suggest the shortest or fastest route to a destination

Given a 2d integer array named triangle with n rows. Its first row has 1 element and each succeeding row has one more element in it than the row above it. Return the minimum falling path sum from the first row to the last.


Movement is allowed only to the bottom or bottom-right cell from the current cell.

Examples:

Input: triangle = [[1], [1, 2], [1, 2, 4]]

Output: 3

Explanation: One possible route can be:

Start at 1st row -> bottom -> bottom.

Input: triangle = [[1], [4, 7], [4,10, 50], [-50, 5, 6, -100]]

Output: -42

Explanation: One possible route can be:

Start at 1st row -> bottom-right -> bottom-right -> bottom-right

Input: triangle = [[3], [-1, 3], [-3, 2, 4], [8, 8, 1, -4]]

Constraints

  • n == number of rows in triangle
  • 1 <= n <= 200
  • -104 <= triangle[i][j] <= 104
  • triangle[0].length == 1
  • triangle[i].length = triangle[i-1].length + 1
  • The answer will not exceed 109

Hints

  • "Each cell’s minimum falling path sum depends on the minimum of its reachable previous row elements. dp[i][j]=triangle[i][j]+min(dp[i−1][j],dp[i−1][j−1]) This ensures we accumulate the smallest possible sum while moving downward."

Company Tags

Roche Micron Technology Swiggy Shopify Etsy OYO Rooms Rockstar Games Deloitte Twilio Dropbox McKinsey & Company Cloudflare Instacart Morgan Stanley AMD Epic Systems Goldman Sachs Pinterest JPMorgan Chase Reddit Flipkart Zoho NVIDIA PayPal Texas Instruments Google Microsoft Amazon Meta Apple Netflix Adobe