Skip to content

Commit 495e466

Browse files
committed
Add solution #363
1 parent 0643250 commit 495e466

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

Diff for: README.md

+1
Original file line numberDiff line numberDiff line change
@@ -286,6 +286,7 @@
286286
354|[Russian Doll Envelopes](./0354-russian-doll-envelopes.js)|Hard|
287287
355|[Design Twitter](./0355-design-twitter.js)|Medium|
288288
357|[Count Numbers with Unique Digits](./0357-count-numbers-with-unique-digits.js)|Medium|
289+
363|[Max Sum of Rectangle No Larger Than K](./0363-max-sum-of-rectangle-no-larger-than-k.js)|Hard|
289290
367|[Valid Perfect Square](./0367-valid-perfect-square.js)|Easy|
290291
371|[Sum of Two Integers](./0371-sum-of-two-integers.js)|Medium|
291292
372|[Super Pow](./0372-super-pow.js)|Medium|
+41
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
/**
2+
* 363. Max Sum of Rectangle No Larger Than K
3+
* https://leetcode.com/problems/max-sum-of-rectangle-no-larger-than-k/
4+
* Difficulty: Hard
5+
*
6+
* Given an m x n matrix matrix and an integer k, return the max sum of a rectangle in the
7+
* matrix such that its sum is no larger than k.
8+
*
9+
* It is guaranteed that there will be a rectangle with a sum no larger than k.
10+
*/
11+
12+
/**
13+
* @param {number[][]} matrix
14+
* @param {number} k
15+
* @return {number}
16+
*/
17+
var maxSumSubmatrix = function(matrix, k) {
18+
let max = -Infinity;
19+
20+
for (let l = 0; l < matrix[0].length; l++) {
21+
const counts = new Array(matrix.length).fill(0);
22+
for (let r = l; r < matrix[0].length; r++) {
23+
for (let i = 0; i < matrix.length; i++) counts[i] += matrix[i][r];
24+
const set = new Set([0]);
25+
let sum = 0;
26+
let value = -Infinity;
27+
for (const num of counts) {
28+
sum += num;
29+
for (const previous of set) {
30+
if (sum - previous <= k) {
31+
value = Math.max(value, sum - previous);
32+
}
33+
}
34+
set.add(sum);
35+
}
36+
max = Math.max(max, value);
37+
}
38+
}
39+
40+
return max;
41+
};

0 commit comments

Comments
 (0)