Diagonal Difference

  • + 0 comments
    public static int diagonalDifference(List<List<Integer>> matrix) {
        int primaryDiagonalSum = 0;
        int secondaryDiagonalSum = 0;
        int n = matrix.size();
        for (int i = 0; i < n; i++) {
            primaryDiagonalSum += matrix.get(i).get(i); // Left-to-right diagonal
            secondaryDiagonalSum += matrix.get(i).get(n - i - 1); // Right-to-left diagonal
        }
        return Math.abs(primaryDiagonalSum - secondaryDiagonalSum);
    }