-
Notifications
You must be signed in to change notification settings - Fork 0
/
Max-Area-histogram.cpp
59 lines (55 loc) · 1.58 KB
/
Max-Area-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
class Solution {
public:
vector<int> NSR(vector<int> arr){
int n = arr.size();
vector<int> ans;
ans.resize(n,-1);
stack<pair<int,int> > st;
for(int i=n-1;i>=0;i--){
while(!st.empty() && st.top().first>=arr[i]){
st.pop();
}
if(!st.empty()){
ans[i] = st.top().second;
}
st.push({arr[i],i});
}
return ans;
}
vector<int> NSL(vector<int> arr){
int n=arr.size();
vector<int> ans; ans.resize(n,-1);
stack<pair<int, int> > st;
for(int i=0;i<n;i++){
while(!st.empty() && st.top().first >= arr[i]){
st.pop();
}
if(!st.empty()){
ans[i] = st.top().second;
}
st.push({arr[i], i});
}
return ans;
}
int largestRectangleArea(vector<int>& heights) {
int n = heights.size();
vector<int> nsl=NSL(heights), nsr=NSR(heights);
vector<int> width;
for(int i=0;i<n;i++){
if(nsl[i]==-1 && nsr[i]==-1){
width.push_back(n);
}else if(nsl[i]==-1){
width.push_back(nsr[i]);
}else if(nsr[i]==-1){
width.push_back(n-nsl[i]-1);
}else{
width.push_back(nsr[i]-nsl[i]-1);
}
}
int ans = INT_MIN;
for(int i=0;i<n;i++){
int currArea = heights[i]*width[i];
ans = max(currArea, ans);
}
return ans;
}