Skip to content

Commit 45f5020

Browse files
committedApr 10, 2025
Add solution #1314
1 parent c89350c commit 45f5020

File tree

2 files changed

+47
-1
lines changed

2 files changed

+47
-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,226 LeetCode solutions in JavaScript
1+
# 1,227 LeetCode solutions in JavaScript
22

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

@@ -995,6 +995,7 @@
995995
1311|[Get Watched Videos by Your Friends](./solutions/1311-get-watched-videos-by-your-friends.js)|Medium|
996996
1312|[Minimum Insertion Steps to Make a String Palindrome](./solutions/1312-minimum-insertion-steps-to-make-a-string-palindrome.js)|Hard|
997997
1313|[Decompress Run-Length Encoded List](./solutions/1313-decompress-run-length-encoded-list.js)|Easy|
998+
1314|[Matrix Block Sum](./solutions/1314-matrix-block-sum.js)|Medium|
998999
1317|[Convert Integer to the Sum of Two No-Zero Integers](./solutions/1317-convert-integer-to-the-sum-of-two-no-zero-integers.js)|Easy|
9991000
1318|[Minimum Flips to Make a OR b Equal to c](./solutions/1318-minimum-flips-to-make-a-or-b-equal-to-c.js)|Medium|
10001001
1319|[Number of Operations to Make Network Connected](./solutions/1319-number-of-operations-to-make-network-connected.js)|Medium|

‎solutions/1314-matrix-block-sum.js

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/**
2+
* 1314. Matrix Block Sum
3+
* https://leetcode.com/problems/matrix-block-sum/
4+
* Difficulty: Medium
5+
*
6+
* Given a m x n matrix mat and an integer k, return a matrix answer where each answer[i][j]
7+
* is the sum of all elements mat[r][c] for:
8+
* - i - k <= r <= i + k,
9+
* - j - k <= c <= j + k, and
10+
* - (r, c) is a valid position in the matrix.
11+
*/
12+
13+
/**
14+
* @param {number[][]} mat
15+
* @param {number} k
16+
* @return {number[][]}
17+
*/
18+
var matrixBlockSum = function(mat, k) {
19+
const rows = mat.length;
20+
const cols = mat[0].length;
21+
const prefixSums = new Array(rows + 1).fill().map(() => new Array(cols + 1).fill(0));
22+
23+
for (let i = 0; i < rows; i++) {
24+
for (let j = 0; j < cols; j++) {
25+
prefixSums[i + 1][j + 1] = prefixSums[i + 1][j]
26+
+ prefixSums[i][j + 1] - prefixSums[i][j] + mat[i][j];
27+
}
28+
}
29+
30+
const result = new Array(rows).fill().map(() => new Array(cols).fill(0));
31+
32+
for (let i = 0; i < rows; i++) {
33+
for (let j = 0; j < cols; j++) {
34+
const top = Math.max(0, i - k);
35+
const bottom = Math.min(rows - 1, i + k);
36+
const left = Math.max(0, j - k);
37+
const right = Math.min(cols - 1, j + k);
38+
39+
result[i][j] = prefixSums[bottom + 1][right + 1]
40+
- prefixSums[bottom + 1][left] - prefixSums[top][right + 1] + prefixSums[top][left];
41+
}
42+
}
43+
44+
return result;
45+
};

0 commit comments

Comments
 (0)
Please sign in to comment.