Skip to content

Commit 7266b8a

Browse files
committed
Add solution #1292
1 parent fac0911 commit 7266b8a

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/**
2+
* 1292. Maximum Side Length of a Square with Sum Less than or Equal to Threshold
3+
* https://leetcode.com/problems/maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold/
4+
* Difficulty: Medium
5+
*
6+
* Given a `m x n` matrix `mat` and an integer `threshold`.
7+
* Return the maximum side-length of a square with a sum less than or equal to `threshold` or return 0 if there is no such square.
8+
*/
9+
10+
/**
11+
* @param {number[][]} mat
12+
* @param {number} threshold
13+
* @return {number}
14+
*/
15+
var maxSideLength = function(mat, threshold) {
16+
let max = 0;
17+
18+
loop1: for (let i = 0; i < mat[0].length; i++) {
19+
loop2: for (let j = 0; j < mat.length; j++) {
20+
if (!mat[j + 1] || !mat[j][i + 1]) { break loop2; }
21+
loop3: for (let s = 1; s < 1000; s++) {
22+
if (!mat[j + s] || !mat[j][i + s] || getSquareSum(mat, i, j, s + 1) > threshold) { break loop3; }
23+
max = Math.max(s + 1, max);
24+
}
25+
}
26+
}
27+
28+
return max;
29+
};
30+
31+
function getSquareSum(mat, i, j, size) {
32+
let sum = 0;
33+
for (let s = 0; s < size; s++) {
34+
mat[j + s].slice(i, i + size).forEach(v => sum += v);
35+
}
36+
return sum;
37+
}

0 commit comments

Comments
 (0)