Skip to content

Commit 1b99fa5

Browse files
committed
Add solution #1572
1 parent 64a26aa commit 1b99fa5

File tree

2 files changed

+32
-1
lines changed

2 files changed

+32
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# 1,375 LeetCode solutions in JavaScript
1+
# 1,376 LeetCode solutions in JavaScript
22

33
[https://leetcodejavascript.com](https://leetcodejavascript.com)
44

@@ -1199,6 +1199,7 @@
11991199
1567|[Maximum Length of Subarray With Positive Product](./solutions/1567-maximum-length-of-subarray-with-positive-product.js)|Medium|
12001200
1568|[Minimum Number of Days to Disconnect Island](./solutions/1568-minimum-number-of-days-to-disconnect-island.js)|Hard|
12011201
1569|[Number of Ways to Reorder Array to Get Same BST](./solutions/1569-number-of-ways-to-reorder-array-to-get-same-bst.js)|Hard|
1202+
1572|[Matrix Diagonal Sum](./solutions/1572-matrix-diagonal-sum.js)|Easy|
12021203
1576|[Replace All ?'s to Avoid Consecutive Repeating Characters](./solutions/1576-replace-all-s-to-avoid-consecutive-repeating-characters.js)|Medium|
12031204
1598|[Crawler Log Folder](./solutions/1598-crawler-log-folder.js)|Easy|
12041205
1657|[Determine if Two Strings Are Close](./solutions/1657-determine-if-two-strings-are-close.js)|Medium|

solutions/1572-matrix-diagonal-sum.js

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
/**
2+
* 1572. Matrix Diagonal Sum
3+
* https://leetcode.com/problems/matrix-diagonal-sum/
4+
* Difficulty: Easy
5+
*
6+
* Given a square matrix mat, return the sum of the matrix diagonals.
7+
*
8+
* Only include the sum of all the elements on the primary diagonal and all the elements on the
9+
* secondary diagonal that are not part of the primary diagonal.
10+
*/
11+
12+
/**
13+
* @param {number[][]} mat
14+
* @return {number}
15+
*/
16+
var diagonalSum = function(mat) {
17+
const n = mat.length;
18+
let sum = 0;
19+
20+
for (let i = 0; i < n; i++) {
21+
sum += mat[i][i];
22+
sum += mat[i][n - 1 - i];
23+
}
24+
25+
if (n % 2 === 1) {
26+
sum -= mat[Math.floor(n / 2)][Math.floor(n / 2)];
27+
}
28+
29+
return sum;
30+
};

0 commit comments

Comments
 (0)