-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path84. Largest Rectangle in Histogram.cpp
61 lines (57 loc) · 1.96 KB
/
84. 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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
class Solution {
public:
vector<int> NSL(vector<int> heights){
vector<int> left;
stack<pair<int,int>> st;
for(int i=0;i<heights.size();i++){
if(st.empty())
left.push_back(-1);
else if(!st.empty() && st.top().first<heights[i])
left.push_back(st.top().second);
else if(!st.empty() && st.top().first>=heights[i]){
while(!st.empty() && st.top().first>=heights[i])
st.pop();
if(st.empty())
left.push_back(-1);
else
left.push_back(st.top().second);
}
st.push({heights[i],i});
}
return left;
}
vector<int> NSR(vector<int> heights){
vector<int> right;
stack<pair<int,int>> st;
for(int i=heights.size()-1;i>=0;i--){
if(st.empty())
right.push_back(heights.size());
else if(!st.empty() && st.top().first<heights[i])
right.push_back(st.top().second);
else if(!st.empty() && st.top().first>=heights[i]){
while(!st.empty() && st.top().first>=heights[i])
st.pop();
if(st.empty())
right.push_back(heights.size());
else
right.push_back(st.top().second);
}
st.push({heights[i],i});
}
reverse(right.begin(),right.end());
return right;
}
int largestRectangleArea(vector<int>& heights) {
vector<int> r = NSR(heights);
vector<int> l = NSL(heights);
vector<int> width;
int mx=0;
for(int i=0;i<heights.size();i++){
width.push_back(r[i]-l[i]-1);
}
for(int i=0;i<heights.size();i++){
mx=max(mx,heights[i]*width[i]);
}
return mx;
}
};