forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0084-largest-rectangle-in-histogram.cpp
44 lines (34 loc) · 1.16 KB
/
0084-largest-rectangle-in-histogram.cpp
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
41
42
43
44
/*
Given array of heights, return area of largest rectangle
Ex. heights = [2,1,5,6,2,3] -> 10 (5 x 2 at index 2 and 3)
Monotonic incr stack, if curr height lower extend back, find max area
Time: O(n)
Space: O(n)
*/
class Solution {
public:
int largestRectangleArea(vector<int>& heights) {
// pair: [index, height]
stack<pair<int, int>> stk;
int result = 0;
for (int i = 0; i < heights.size(); i++) {
int start = i;
while (!stk.empty() && stk.top().second > heights[i]) {
int index = stk.top().first;
int width = i - index;
int height = stk.top().second;
stk.pop();
result = max(result, height * width);
start = index;
}
stk.push({start, heights[i]});
}
while (!stk.empty()) {
int width = heights.size() - stk.top().first;
int height = stk.top().second;
stk.pop();
result = max(result, height * width);
}
return result;
}
};