forked from codedecks-in/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmatrix-diagonal-sum.java
More file actions
29 lines (25 loc) · 798 Bytes
/
matrix-diagonal-sum.java
File metadata and controls
29 lines (25 loc) · 798 Bytes
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
/**
* Given a square matrix mat, return the sum of the matrix diagonals.
*
* Only include the sum of all the elements on the primary diagonal and all the elements on the secondary diagonal that are not part of the primary diagonal.
*
* Time Complexity - O(n)
* Space Complexity - O(1)
*/
class Solution {
public int diagonalSum(int[][] mat) {
int diagonalSum = 0;
int len = mat.length - 1;
for(int i=0; i<mat.length; i++){
for(int j=0; j<mat[i].length; j++){
if(i == j){
diagonalSum += mat[i][j];
}
else if(i == (len-j)){
diagonalSum += mat[i][j];
}
}
}
return diagonalSum;
}
}