Skip to content

Instantly share code, notes, and snippets.

@tatsuyax25
Created September 25, 2025 17:26
Show Gist options
  • Select an option

  • Save tatsuyax25/351d73c6459b951645c062c404318447 to your computer and use it in GitHub Desktop.

Select an option

Save tatsuyax25/351d73c6459b951645c062c404318447 to your computer and use it in GitHub Desktop.
Given a triangle array, 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
/**
* @param {number[][]} triangle
* @return {number}
*/
var minimumTotal = function(triangle) {
// Start from the second-to-last row and move upward
for (let row = triangle.length - 2; row >= 0; row--) {
for (let col = 0; col < triangle[row].length; col++) {
// For each element, choose the minimum of the two adjacent numbers in the row below
// and add it to the current element
triangle[row][col] += Math.min(
triangle[row + 1][col], // directly below
triangle[row + 1][col + 1] // below and to the right
);
}
}
// After processing, the top element contains the minimum path sum
return triangle[0][0];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment