-
Notifications
You must be signed in to change notification settings - Fork 181
/
Copy pathlargest.cpp
50 lines (46 loc) · 1.1 KB
/
largest.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
#include <iostream>
#include <vector>
#include <stack>
using namespace std;
vector<int> nearestSmallerOnRight(vector<int>& heights) {
stack<int>st;
vector<int>ans(heights.size(),heights.size());
for(int i=0;i<heights.size();i++)
{
while(!st.empty() && heights[i]<heights[st.top()])
{
ans[st.top()]=i;
st.pop();
}
st.push(i);
}
return ans;
}
vector<int> nearestSmallerOnLeft(vector<int>& heights)
{
stack<int>st;
vector<int>ans(heights.size(),-1);
for(int i=heights.size()-1;i>=0;i--)
{
while(!st.empty() && heights[i]<heights[st.top()])
{
ans[st.top()]=i;
st.pop();
}
st.push(i);
}
return ans;
}
int largestRectangleArea(vector<int>& heights)
{
vector<int>NSR=nearestSmallerOnRight(heights);
vector<int>NSL=nearestSmallerOnLeft(heights);
int ans=0;
for(int i=0;i<heights.size();i++)
ans=max(ans,(NSR[i]-NSL[i]-1)*heights[i]);
return ans;
}
int main() {
vector<int> vec = {2, 1, 5, 6, 2, 3};
cout << largestRectangleArea(vec);
}