Diagonal Difference

  • + 1 comment

    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.

    public static void main(String[] args) {
            Scanner in = new Scanner(System.in);
            
            int N = in.nextInt();
            int sumA =0, sumB = 0;
            int M = N*N;
            //counter for first diagonal
            int countA = N-N;  // 0   -> N*N  ; step N+1  
            // counte for second diagonal
            int countB = N-1;  // N-1 -> N*N-N; step N-1 
            int countBLimit = M-1; // the last element is not for this diagonal 
            
            for (int i = 0; i<M; i++) {
                int k = 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)); 
        }