I’ve done project euler’s max triangle sum problem and I dont understand why it keeps changing the global variable, when i remove the function call all the tests pass, I mean, i created a copy of triangle and even tried using a for loop to push, why cant it be like C++ when you need reference to change it?? oof.
how do you make the function not change the global? var arr = triangle doesn’t seem to work either
function maximumPathSumI(triangle) {
var arr = [...triangle];
var arrLen = arr.length-2;
for(let i = arrLen; i >= 0; i--) {
for(let j = i; j >= 0; j--) {
arr[i][j] += Math.max(arr[i+1][j], arr[i+1][j+1]);
}
}
return arr[0][0];
}
const testTriangle = [[3, 0, 0, 0],
[7, 4, 0, 0],
[2, 4, 6, 0],
[8, 5, 9, 3]];
maximumPathSumI(testTriangle)
console.log(testTriangle); /*[ [ 23, 0, 0, 0 ],
[ 20, 19, 0, 0 ],
[ 10, 13, 15, 0 ],
[ 8, 5, 9, 3 ] ]*/
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36.
Challenge: Problem 18: Maximum path sum I
Link to the challenge: