-
Notifications
You must be signed in to change notification settings - Fork 37
/
largestRectangleInHistogram.cpp
58 lines (47 loc) · 1.29 KB
/
largestRectangleInHistogram.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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
class Solution {
private:
vector<int> nextSmallerElements(vector<int> &heights,int n){
stack<int> st;
st.push(-1);
vector<int> ans(n);
for(int i=n-1; i>=0; i--){
while(st.top()!= -1 && heights[st.top()]>=heights[i]){
st.pop();
}
ans[i] = st.top();
st.push(i);
}
return ans;
}
vector<int> prevSmallerElements(vector<int> &heights,int n){
stack<int> st;
st.push(-1);
vector<int> ans(n);
for(int i=0; i<n; i++){
while(st.top()!= -1 && heights[st.top()]>=heights[i]){
st.pop();
}
ans[i] = st.top();
st.push(i);
}
return ans;
}
public:
int largestRectangleArea(vector<int>& heights) {
int n = heights.size();
vector<int> next(n);
next = nextSmallerElements(heights, n);//indices
vector<int> prev(n);
prev = prevSmallerElements(heights, n);
int area = INT_MIN;
for(int i=0; i<n; i++){
int l = heights[i];
if(next[i] == -1){
next[i] = n;
}
int b = next[i] - prev[i] -1;
area = max(area, l*b);
}
return area;
}
};