-
Notifications
You must be signed in to change notification settings - Fork 111
/
solution.cpp
62 lines (51 loc) · 1.26 KB
/
solution.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#include <bits/stdc++.h>
using namespace std;
/*
* the 'diagonalDifference' function below.
*
* The function is expected to return an INTEGER.
* The function accepts 2D_INTEGER_ARRAY arr as parameter.
*
* Complexity: BigO(n);
*
* What we do is traversing one diagonal at a time, because traversin 2 diagonals in onemay complicate things
*
* In first loop, we traverse from left top to right bottom whereas
* in 2nd loop we will traverse from right top to bottom left
*/
int diagonalDifference(vector<vector<int>> arr) {
int s1=0; //sum of diagonal from left top to right bottom
int n=arr[0].size(); //size of square matrix
int i=0;
//loop 1
while(i<n){
s1=s1+arr[i][i];
i++;
}
//loop 2
int s2=0,j=n-1; //sum of diagonal from right top to left bottom
i=0;
while(i<n){
s2=s2+arr[i][j];
i++;
j--;
}
return abs(s2-s1); //difference of solution;
}
int main()
{
int n;
cin>>n;
vector<vector<int>> arr(n);
for (int i = 0; i < n; i++) {
arr[i].resize(n);
for (int j = 0; j < n; j++) {
int a;
cin>>a;
arr[i][j] = a;
}
}
int result = diagonalDifference(arr);
cout << result << "\n";
return 0;
}