forked from prateekshyap/DSA
-
Notifications
You must be signed in to change notification settings - Fork 0
/
LC_84_LargestRectangleInHistogram.cpp
133 lines (108 loc) · 3.44 KB
/
LC_84_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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
/*
https://leetcode.com/problems/largest-rectangle-in-histogram/
84. Largest Rectangle in Histogram
https://practice.geeksforgeeks.org/problems/maximum-rectangular-area-in-a-histogram-1587115620/1
*/
class Solution {
public:
int largestRectangleArea_1(vector<int>& heights) {
int n = heights.size();
vector<int> leftSmaller(n, -1), rightSmaller(n, n);
stack<int> st;
int ans=0, area=0;
for(int i=0; i<n; i++)
{
while(!st.empty() && heights[i] <= heights[st.top()])
st.pop();
if(!st.empty())
leftSmaller[i] = st.top();
st.push(i);
}
// for(int x: leftSmaller)
// cout<<x<<" ";
while(!st.empty())
st.pop();
for(int i=n-1; i>=0; i--)
{
while(!st.empty() && heights[i] <= heights[st.top()])
st.pop();
if(!st.empty())
rightSmaller[i] = st.top();
st.push(i);
}
// cout<<endl;
// for(int x: rightSmaller)
// cout<<x<<" ";
// cout<<endl;
for(int i=0; i<n; i++)
{
area = (rightSmaller[i] - leftSmaller[i]-1)*heights[i];
// cout<<area<<" ";
if(area> ans)
ans = area;
}
return ans;
}//end
int largestRectangleArea_2(vector<int>& heights) {
int n = heights.size();
vector<int> leftSmaller(n, -1), rightSmaller(n, n);
// stack<int> st;
int ans=0, area=0, pre=0;
for(int i=1; i<n; i++)
{
pre=i-1;
while(pre>=0 && heights[pre] >= heights[i])
pre = leftSmaller[pre];
leftSmaller[i] = pre;
}
// for(int x: leftSmaller)
// cout<<x<<" ";
for(int i=n-2; i>=0; i--)
{
pre = i+1;
while(pre<n && heights[i] <= heights[pre])
pre = rightSmaller[pre];
rightSmaller[i] = pre;
}
// cout<<endl;
// for(int x: rightSmaller)
// cout<<x<<" ";
// cout<<endl;
for(int i=0; i<n; i++)
{
area = (rightSmaller[i] - leftSmaller[i]-1)*heights[i];
// cout<<area<<" ";
if(area> ans)
ans = area;
}
return ans;
}//end
int largestRectangleArea(vector<int>& heights) {
int n = heights.size();
stack<int> st;
int ans=0, h;
for(int i=0; i<n; i++)
{
while(!st.empty() && heights[st.top()] > heights[i])
{
h = heights[st.top()]; st.pop();
if(st.empty())
ans = max(ans, i*h);
else
ans = max(ans, h*(i-st.top()-1));
// cout<<i<<" "<<h<<" "<<ans<<endl;
}
st.push(i);
}
while(!st.empty() && heights[st.top()] > 0)
{
h = heights[st.top()]; st.pop();
if(st.empty())
ans = max(ans, n*h);
else
ans = max(ans, h*(n-st.top()-1));
// cout<<n<<" "<<h<<" "<<ans<<endl;
}
return ans;
}//end
};