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.
After all, the best method is brute force. The idea is simple, you only need to travese the grid to find possible plus and then loop through these valid pluses to get the max product. Here is my js for the function. It might not be optimized, so feel free to upgrade it further.
functionisCellValid(grid,i,j){if(!grid[i]||!grid[i][j])returnfalse;if(grid[i][j]==='G')returntrue;elsereturnfalse;}functionisPlusOverlap(plus1,plus2){const{i:i1,j:j1,count:count1}=plus1;const{i:i2,j:j2,count:count2}=plus2;letplusArr1=[];letplusArr2=[];for(leti=i1-count1+1;i<=i1+count1-1;i++){plusArr1.push({i,j:j1});}for(letj=j1-count1+1;j<=j1+count1;j++){plusArr1.push({i:i1,j});}for(leti=i2-count2+1;i<=i2+count2-1;i++){plusArr2.push({i,j:j2});}for(letj=j2-count2+1;j<=j2+count2-1;j++){plusArr2.push({i:i2,j});}constintersection=plusArr1.reduce((acc,value)=>{letfilteredArr=plusArr2.filter(obj=>obj.i===value.i&&obj.j===value.j)if(filteredArr.length>0){acc.push([...filteredArr]);}returnacc;},[]);if(intersection.length>0)returntrue;returnfalse;}functiontwoPluses(grid){// Write your code hereleth=grid.length;letw=grid[0].length;letplusses=[];letoutput=0;for(leti=1;i<h-1;i++){for(letj=1;j<w-1;j++){if(isCellValid(grid,i,j)){letcount=0;while(isCellValid(grid,i-count,j)&&isCellValid(grid,i+count,j)&&isCellValid(grid,i,j-count)&&isCellValid(grid,i,j+count)){count++;plusses.push({i,j,count})}}}}for(letk=0;k<plusses.length-1;k++){letplus=plusses[k];letproduct=0;for(leth=k+1;h<plusses.length;h++){letplus2=plusses[h];if(!isPlusOverlap(plus,plus2)){lettempProduct=(1+4*(plus.count-1))*(1+4*(plus2.count-1));if(product<tempProduct){product=tempProduct;console.log(plus,plus2,product);}}}if(output<product)output=product;}returnoutput;}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
An unexpected error occurred. Please try reloading the page. If problem persists, please contact support@hackerrank.com
Ema's Supercomputer
You are viewing a single comment's thread. Return to all comments →
After all, the best method is brute force. The idea is simple, you only need to travese the grid to find possible plus and then loop through these valid pluses to get the max product. Here is my js for the function. It might not be optimized, so feel free to upgrade it further.