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.

Yes, it is a good thinking .. If anyone has read Herbert Schildt or Deitel's Java books would have recognized it..
my solution is the same.. some one else should be able to read it quickly..

static int diagonalDifference(int[][] a) {
int primeDi = 0, secondDi = 0;
// could be improved to
// int sum = 0;
for (int i = 0 , j = a[0].length-1; i < a[0].length ; i++, j--) {
primeDi += a[i][i] ;
secondDi += a[i][j] ;
// could be improved to
// sum = a[i][i] - a[i][j] ;
}
return Math.abs(primeDi - secondDi);
// could be improved to
// return Math.abs(sum);
}

Should not the sum be: sum = sum + (a[i][i] - a[i][j]) I have tried to run like you commented but I got wrong answers. The previous sum needs to be taken into account I think before calculating the new one.

## Diagonal Difference

You are viewing a single comment's thread. Return to all comments →

Yes, it is a good thinking .. If anyone has read Herbert Schildt or Deitel's Java books would have recognized it.. my solution is the same.. some one else should be able to read it quickly..

This comment has helped me understand not only the solution, but

howto get to the solution. From a rookie programmer, thank you for the insight!this is awesome thanks

Should not the sum be: sum = sum + (a[i][i] - a[i][j]) I have tried to run like you commented but I got wrong answers. The previous sum needs to be taken into account I think before calculating the new one.