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.
functionmain(){letarr=Array(6);for(leti=0;i<6;i++){arr[i]=readLine().replace(/\s+$/g,'').split(' ').map(arrTemp=>parseInt(arrTemp,10));}console.log(maxHourglassSum(arr));}functionmaxHourglassSum(arr){constrows=arr.length;constcols=arr[0].length;// Handle cases where the array is smaller than 3x3if(rows<3||cols<3)returnnull;letmaxSum=-Infinity;// Initialize to the smallest possible value// Loop through the top-left corners of the possible hourglassesfor(leti=0;i<=rows-3;i++){for(letj=0;j<=cols-3;j++){// Calculate the hourglass sumletsum=arr[i][j]+arr[i][j+1]+arr[i][j+2]// Top row+arr[i+1][j+1]// Middle element+arr[i+2][j]+arr[i+2][j+1]+arr[i+2][j+2];// Bottom row// Update maxSum if the current hourglass sum is greaterif(sum>maxSum){maxSum=sum;}}}returnmaxSum;}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Day 11: 2D Arrays
You are viewing a single comment's thread. Return to all comments →
Here's my javascript solution:-