-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMaxAreaHistogram.cpp
64 lines (57 loc) · 1.28 KB
/
MaxAreaHistogram.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
62
63
64
//TC = O(n)
//SC = O(n)
#include <bits/stdc++.h>
#include <vector>
#include <string>
#include <math.h>
using namespace std;
#define ll long long
#define IOS ios_base::sync_with_stdio(false);
#define print(array) \
for (auto it : array) \
cout << it << " "
#define sortit(array) sort(array.begin(), array.end())
const int M = 1e9 + 7;
int largestRectangleArea(vector<int>& heights) {
int n =heights.size();
vector<int> leftsmall(n,0);
vector<int> rightsmall(n,n-1);
stack<int> st;
for(int i =0;i<n;i++)
{
while(!st.empty() && heights[st.top()]>=heights[i])
{
st.pop();
}
if(!st.empty()) leftsmall[i] = st.top()+1;
st.push(i);
}
while(!st.empty())
{
st.pop();
}
for(int i =n-1;i>=0;i--)
{
while(!st.empty() && heights[st.top()]>=heights[i])
{
st.pop();
}
if(!st.empty()) rightsmall[i] = st.top()-1;
st.push(i);
}
while(!st.empty())
{
st.pop();
}
int maxi=0;
for(int i =0;i<n;i++)
{
maxi = max(maxi, (rightsmall[i]-leftsmall[i]+1)*heights[i]);
}
return maxi;
}
int main()
{
vector<int> heights = {2,1,5,6,2,3};
cout<<largestRectangleArea(heights);
}