Diagonal Difference | Solved | Java
Given a square matrix, calculate the absolute difference between the sums of its diagonals.
For example, the square matrix is shown below:
1 2 3
4 5 6
9 8 9
- The left-to-right diagonal = .
- The right-to-left diagonal = .
Their absolute difference is .
Function description
Complete the function with the following parameter:
- : a 2-D array of integers
Return
- : the absolute difference in sums along the diagonals
Input Format
The first line contains a single integer, , the number of rows and columns in the square matrix .
Each of the next lines describes a row, , and consists of space-separated integers .
Solution:
public static int diagonalDifference(List<List<Integer>> arr) {
// Write your code here
int sum = 0;
int sum1 = 0;
int m = arr.size() - 1;
for (List<Integer> i : arr) {
int k = 0;
for (Integer j : i) {
if (k == arr.get(0).size() - 1 - m) {
sum = sum + i.get(k);
}
if (m == arr.get(0).size() - 1 - k) {
sum1 = sum1 + i.get(m);
}
k++;
}
m--;
}
return Math.abs(sum1 - sum);
}
Comments
Post a Comment