Coding Test/HackerRank
[HackerRank] Diagonal Difference c++
owls
2022. 7. 16. 20:58
728x90
- problem
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 = 1 + 5 + 9. The right to left diagonal = 3 +5 +9. Their absolute difference is |15-17| = 2.
- sample input
3
11 2 4
4 5 6
10 8 -12
- output
15
- solution
왼쪽방향 대각선, 오른쪽 방향 대각선의 원소들의 합을 구한뒤 둘의 차를 구하는 문제이다.
sample input을 기준으로
오른쪽 방향 대각선은 원소의 위치가 [0][0],[1][1],[2][2] -> 규칙을 가지고 있고,
왼쪽 방향 대각선은 [0][2] , [1][1], [2][0] -> 규칙을 가지고 있다.
이 규칙을 코드화 시키면 아래와 같이 나온다.
int diagonalDifference(vector<vector<int>> arr) {
int n = arr.size(), result = 0, left = 0, right = 0;
for(int i = 0; i < n; i++){
left += arr[i][i];
right += arr[i][n-i-1];
}
result = abs(left - right);
return result;
}
728x90