Skip to content

Commit ed8022a

Browse files
committed
feat: Largest Rectangle in Histogram
1 parent 0050c72 commit ed8022a

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
// 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.
2+
//
3+
// |
4+
// | |
5+
// | |
6+
// | | |
7+
// | | | | |
8+
// | | | | | |
9+
//
10+
// Above is a histogram where width of each bar is 1, given height = [2,1,5,6,2,3].
11+
// The largest rectangle is shown in the shaded area, which has area = 10 unit.
12+
//
13+
// Example:
14+
//
15+
// Input: [2,1,5,6,2,3]
16+
// Output: 10
17+
18+
/**
19+
* @param {number[]} heights
20+
* @return {number}
21+
*/
22+
23+
/** Monotonic Stack */
24+
// https://youtu.be/KkJrGxuQtYo?t=479
25+
// Time O(n)
26+
// Space O(n)
27+
//
28+
// Last pop() is hIdx
29+
// Then peak() is lIdx
30+
//
31+
// st hIdx lIdx rIdx h w area max
32+
// [0]
33+
// [] 0 U 1 2 1 2 2
34+
// [1]
35+
// [1,2]
36+
// [1,2,3]
37+
// [1,2] 3 2 4 6 1 6 6
38+
// [1] 2 1 4 5 2 10 10
39+
// [1,4]
40+
// [1,4,5]
41+
// [1,4] 5 4 6 3 1 3 10
42+
// [1] 4 1 6 2 4 8 10
43+
// [] 1 U 6 1 6 6 10
44+
const largestRectangleArea = (heights) => {
45+
const st = [];
46+
47+
const getArea = (rIdx) => {
48+
const hIdx = st.pop();
49+
const h = heights[hIdx];
50+
51+
const lIdx = st[st.length - 1];
52+
53+
const w = st.length ? rIdx - lIdx - 1 : rIdx;
54+
return w * h;
55+
};
56+
57+
let max = 0;
58+
for (let rIdx = 0; rIdx < heights.length; rIdx++) {
59+
while (st.length && heights[rIdx] < heights[st[st.length - 1]]) {
60+
const area = getArea(rIdx);
61+
max = Math.max(max, area);
62+
}
63+
st.push(rIdx);
64+
}
65+
while (st.length) {
66+
const area = getArea(heights.length);
67+
max = Math.max(max, area);
68+
}
69+
return max;
70+
};

0 commit comments

Comments
 (0)