Skip to content

Commit 5c651e3

Browse files
DiagonalSum is added
1 parent c3202c1 commit 5c651e3

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
package ArrayBasedProblems;
2+
3+
public class DiagonalSum {
4+
public static void main(String[] args) {
5+
int[][] matrix = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
6+
System.out.println("Diagonal sum: " + diagonalSum(matrix));
7+
}
8+
9+
public static int diagonalSum(int[][] matrix) { // O(n) time and O(1) space
10+
int sum = 0;
11+
for (int i = 0; i < matrix.length; i++) {
12+
sum += matrix[i][i];
13+
if (i != matrix.length - i - 1) {
14+
sum += matrix[i][matrix.length - i - 1];
15+
}
16+
}
17+
return sum;
18+
}
19+
20+
public int bruceForce(int[][] mat) { // O(n^2) time and O(1) space
21+
int sum = 0;
22+
int col = mat[0].length-1;
23+
for(int i =0;i<mat.length;i++) {
24+
for(int j = 0;j<mat[0].length;j++) {
25+
if(i==j || j==(col-i)){
26+
System.out.println(mat[i][j]);
27+
sum += mat[i][j];
28+
}
29+
}
30+
}
31+
return sum;
32+
}
33+
}

0 commit comments

Comments
 (0)