We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
I really put in some effort on this one to optimize it. LMK if you see any optimizations I could make:
//Each non-edge node is visited at least twice so caching saves a ton of timelettriangleCache={};//Derived from the triangular number formulaletgetRowOfIdx=idx=>Math.floor(-0.5+Math.sqrt(0.25+(2*idx)));letcalculateMaxSum=(triangle,n=0)=>{if(n>=triangle.length)return0;if(triangleCache[n])returntriangleCache[n];letleft=triangle[n]+calculateMaxSum(triangle,n+getRowOfIdx(n)+1);letright=triangle[n]+calculateMaxSum(triangle,n+getRowOfIdx(n)+2);triangleCache[n]=Math.max(left,right);returntriangleCache[n];}functionprocessData(input){letdata=input.split('\n');letnumCases=data.shift();for(leti=0;i<numCases;i++){letnumRows=data.shift();letrows=[];for(letj=0;j<numRows;j++){rows.push(...data.shift().split(' ').map(v=>parseInt(v)));}console.log(calculateMaxSum(rows));triangleCache={};}}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Project Euler #18: Maximum path sum I
You are viewing a single comment's thread. Return to all comments →
I really put in some effort on this one to optimize it. LMK if you see any optimizations I could make: