forked from striver79/SDESheet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlargestRectangleHistorgram2passCpp
37 lines (31 loc) · 1.02 KB
/
largestRectangleHistorgram2passCpp
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
class Solution {
public:
int largestRectangleArea(vector<int>& heights) {
int n = heights.size();
stack<int> st;
int leftSmall[n], rightSmall[n];
for(int i = 0;i<n;i++) {
while(!st.empty() && heights[st.top()] >= heights[i]) {
st.pop();
}
if(st.empty()) leftSmall[i] = 0;
else leftSmall[i] = st.top() + 1;
st.push(i);
}
// clear the stack to be re-used
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] = n-1;
else rightSmall[i] = st.top() - 1;
st.push(i);
}
int maxA = 0;
for(int i = 0;i<n;i++) {
maxA = max(maxA, heights[i] * (rightSmall[i] - leftSmall[i] + 1));
}
return maxA;
}
};