Skip to content

Commit f66637e

Browse files
committed
Add solution #1504
1 parent 257c531 commit f66637e

File tree

2 files changed

+41
-1
lines changed

2 files changed

+41
-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,333 LeetCode solutions in JavaScript
1+
# 1,334 LeetCode solutions in JavaScript
22

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

@@ -1149,6 +1149,7 @@
11491149
1499|[Max Value of Equation](./solutions/1499-max-value-of-equation.js)|Hard|
11501150
1502|[Can Make Arithmetic Progression From Sequence](./solutions/1502-can-make-arithmetic-progression-from-sequence.js)|Easy|
11511151
1503|[Last Moment Before All Ants Fall Out of a Plank](./solutions/1503-last-moment-before-all-ants-fall-out-of-a-plank.js)|Medium|
1152+
1504|[Count Submatrices With All Ones](./solutions/1504-count-submatrices-with-all-ones.js)|Medium|
11521153
1507|[Reformat Date](./solutions/1507-reformat-date.js)|Easy|
11531154
1512|[Number of Good Pairs](./solutions/1512-number-of-good-pairs.js)|Easy|
11541155
1519|[Number of Nodes in the Sub-Tree With the Same Label](./solutions/1519-number-of-nodes-in-the-sub-tree-with-the-same-label.js)|Medium|
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
/**
2+
* 1504. Count Submatrices With All Ones
3+
* https://leetcode.com/problems/count-submatrices-with-all-ones/
4+
* Difficulty: Medium
5+
*
6+
* Given an m x n binary matrix mat, return the number of submatrices that have all ones.
7+
*/
8+
9+
/**
10+
* @param {number[][]} mat
11+
* @return {number}
12+
*/
13+
var numSubmat = function(mat) {
14+
const rows = mat.length;
15+
const cols = mat[0].length;
16+
const heights = new Array(cols).fill(0);
17+
let result = 0;
18+
19+
for (let i = 0; i < rows; i++) {
20+
const stack = [];
21+
for (let j = 0; j < cols; j++) {
22+
heights[j] = mat[i][j] === 1 ? heights[j] + 1 : 0;
23+
24+
while (stack.length && heights[j] <= heights[stack[stack.length - 1]]) {
25+
stack.pop();
26+
}
27+
28+
stack.push(j);
29+
30+
for (let k = 0; k < stack.length; k++) {
31+
const height = heights[stack[k]];
32+
const width = k === 0 ? stack[k] + 1 : stack[k] - stack[k - 1];
33+
result += height * width;
34+
}
35+
}
36+
}
37+
38+
return result;
39+
};

0 commit comments

Comments
 (0)