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.
My attempt, annotated for complete beginners to understand:
publicclassSolution{publicstaticvoidmain(String[]args){Scannerin=newScanner(System.in);intmatrix[][]=newint[6][6];//Read in:for(inti=0;i<6;i++){for(intj=0;j<6;j++){matrix[i][j]=in.nextInt();}}intmaxSum=-64;//Because the minimum it could be is -9*7 = -63intstartCol=0;//Each iteration of the outer loop is one hour glass:for(introw=0;row<=3;row++){intsum=0;//Initialize this specific hourglass' sumfor(intcol=startCol;col<startCol+3;col++){sum+=matrix[row][col];//Gets current index that col and row are onif(col==startCol){//Only doing it if it's on the startCol ensures we only add middle piece oncesum+=matrix[row+1][startCol+1];}sum+=matrix[row+2][col];//Gets the corresponding index in the bottom row}startCol=(startCol<3)?startCol+1:0;// If there is space for another hourglass in this row, goto // the next Colif(startCol!=0){//If there is space for another hourglass in this row, continue in the same rowrow--;//You need to decrement in order to do this bc for loop will increment}if(sum>maxSum){maxSum=sum;}//keeps track of what the maximum sum is so we can print it at the end}System.out.println(maxSum);}}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
2D Array - DS
You are viewing a single comment's thread. Return to all comments →
My attempt, annotated for complete beginners to understand: