Skip to content

Commit ac3bf1f

Browse files
committed
84-Largest-Rectangle-in-Histogram
1 parent c6c768d commit ac3bf1f

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
/**
2+
* @param {number[]} heights
3+
* @return {number}
4+
*/
5+
var largestRectangleArea = function(heights) {
6+
let largestArea = 0;
7+
let stack = [];
8+
9+
for (let i = 0; i< heights.length; i++){
10+
let start = i;
11+
12+
while ( stack.length > 0 && stack[stack.length-1][1] > heights[i] ){
13+
let [lastI, lastH] = stack.pop();
14+
largestArea = Math.max(largestArea, lastH * (i-lastI));
15+
start = lastI;
16+
}
17+
18+
stack.push([ start, heights[i] ]);
19+
}
20+
21+
for (let j = 0; j < stack.length; j++){
22+
let currArea = stack[j][1] * (heights.length - stack[j][0]);
23+
largestArea = Math.max(largestArea, currArea);
24+
}
25+
26+
return largestArea;
27+
};

0 commit comments

Comments
 (0)