freeCodeCamp Challenge Guide: Problem 67: Maximum path sum II

Problem 67: Maximum path sum II


Solutions

Solution 1 (Click to Show/Hide)
  // Copy the triangle
  //   Note: not needed if we are ok with mutating the input
  const triangleCopy = triangle.map(row => [...row]);
  // Find max path
  for (let i = triangleCopy.length - 2; i >= 0; i--) {
    for (let j = 0; j <= i; j++) {
      triangleCopy[i][j] += Math.max(triangleCopy[i + 1][j], triangleCopy[i + 1][j + 1]);
    }
  }
  return triangleCopy[0][0];
}

Note that the same solution for Project Euler Problem 18 can be reused if you did not use a brute-force approach.