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.
This is a solution where we go through the matrix only once, no arrays just check if we add the number to one of the diagonals or both.
publicstaticvoidmain(String[]args){Scannerin=newScanner(System.in);intN=in.nextInt();intsumA=0,sumB=0;intM=N*N;//counter for first diagonalintcountA=N-N;// 0 -> N*N ; step N+1 // counte for second diagonalintcountB=N-1;// N-1 -> N*N-N; step N-1 intcountBLimit=M-1;// the last element is not for this diagonal for(inti=0;i<M;i++){intk=in.nextInt();if(i==countA){sumA+=k;countA+=N+1;}if(i==countB&&countB<countBLimit){sumB+=k;countB+=N-1;}}System.out.println(Math.abs(sumA-sumB));}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Diagonal Difference
You are viewing a single comment's thread. Return to all comments →
This is a solution where we go through the matrix only once, no arrays just check if we add the number to one of the diagonals or both.