JSFiddle - React, Tailwind, and code Playground
by Sevgen
JavaScript
const mountain = [
[6],
[7, 10],
[12, 11, 9],
[90, 25, 13, 14]
];
function findPath(mountain) {
const rows = mountain.length;
const dp = new Array(rows).fill(0).map(() => new Array(rows).fill(0));
// Initialize the last row of dp with the mountain values
for (let i = 0; i < rows; i++) {
dp[rows - 1][i] = mountain[rows - 1][i];
}
// Dynamic programming: start from the second-to-last row
for (let i = rows - 2; i >= 0; i--) {
for (let j = 0; j <= i; j++) {
dp[i][j] = mountain[i][j] + Math.max(dp[i + 1][j], dp[i + 1][j + 1]);
}
}
return dp[0][0];
}
console.log(findPath(mountain)); // Очікуваний результат: 115