forked from rubythonode/javascript-problems-and-solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlargest-rectangle-in-histogram.js
More file actions
40 lines (32 loc) · 900 Bytes
/
largest-rectangle-in-histogram.js
File metadata and controls
40 lines (32 loc) · 900 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/**
* Largest Rectangle in Histogram
*
* Given n non-negative integers representing the histogram's bar height where the width of each bar is 1, find the
* area of largest rectangle in the histogram.
*
* Example:
*
* Input: [2,1,5,6,2,3]
* Output: 10
*/
import Stack from 'common/stack';
/**
* @param {number[]} heights
* @return {number}
*/
const largestRectangleArea = heights => {
const n = heights.length;
const stack = new Stack();
let max = 0;
for (let i = 0; i <= n; i++) {
// If we finished all the elements OR the current element is less than top
while (!stack.isEmpty() && (i === n || heights[i] < heights[stack.peek()])) {
const height = heights[stack.pop()];
const width = stack.isEmpty() ? i : i - 1 - stack.peek();
max = Math.max(max, width * height);
}
stack.push(i);
}
return max;
};
export { largestRectangleArea };