Diagonal Difference

 

Diagonal Difference

 

Given a square matrix, calculate the absolute difference between the sums of its diagonals.

For example, the square matrix arr is shown below:

1 2 3
4 5 6
9 8 9  

The left-to-right diagonal = 1+5+9=15. The right to left diagonal = 3+5+9=17. Their absolute difference is |15-17|=2

Sample Input

3
11 2 4
4 5 6
10 8 -12

Sample Output

15

Explanation

The primary diagonal is:

11
   5
     -12

Sum across the primary diagonal: 11 + 5 - 12 = 4

The secondary diagonal is:

     4
   5
10

Sum across the secondary diagonal: 4 + 5 + 10 = 19
Difference: |4 - 19| = 15


Algo:

1.We take two pointer i.e variable i,j to traverse the matrix.To sum the left diagonal assign i=0,j=0 .

2. To sum the right diagonal, make j as "n-1" and i=0, it will point to the last element in the first row , and now decrement j and increment i to add all diagonal values.
 
3.Finally return the difference between them

Code:

public static int diagonalDifference(List<List<Integer>> arr) {
        int sum1=0;
        int sum2=0;
        int n=arr.size();
        int i=0,j=0;

    while(i<n && j<n)
    {
        //positive diagonal sum "top left to bottom right"
        sum1+=arr.get(i++).get(j++);
    }

    i=0;
    j=n-1;
    
    while(i<n && j>=0)
    {
        //"top right to bottom left"
        sum2+=arr.get(i++).get(j--);
    }
    
        return Math.abs(sum1-sum2);
    }
}
 

Post a Comment

0 Comments