Diagonal Difference [Hacker Rank]

Kim Hayeon·2023년 4월 24일
0

Algorithm Study

목록 보기
11/37
post-thumbnail

Question

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 = 15. The right to left diagonal = 17. Their absolute difference is 2.

Function description

Complete the diagonalDifference function in the editor below.

diagonalDifference takes the following parameter:

  • int arr[n][m]: an array of integers

Return

  • int: the absolute diagonal difference

Input Format

The first line contains a single integer, n , the number of rows and columns in the square matrix arr.
Each of the next lines describes a row, , and consists of space-separated integers .

Constraints

  • -100 <= arr[i][j] <= 100

Output Format

Return the absolute difference between the sums of the matrix's two diagonals as a single integer.

Code

def diagonalDifference(arr):
    # Write your code here
    la = len(arr)
    a = 0
    b = 0
    for i in range(la):
        a += arr[i][i]
        b += arr[i][la-1-i]
    return abs(a-b)


left-to-right diagonal 합은 i==j 일 때의 합이고, The right to left diagonal 합은 i+j == len(arr)-1 일 때의 합이다.

profile
우리는 무엇이든 될 수 있어

0개의 댓글