-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path84.largest-rectangle-in-histogram.cpp
More file actions
83 lines (66 loc) · 2.07 KB
/
84.largest-rectangle-in-histogram.cpp
File metadata and controls
83 lines (66 loc) · 2.07 KB
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
class Solution {
public:
void print1d(vector<int> &nums){
for(auto i: nums){
cout<<i<<" ";
}
cout<<"\n--------\n";
}
int largestRectangleArea(vector<int>& heights) {
int n = heights.size();
// left
vector<int> left(n);
// index, value
stack<int> st;
for(int i = 0; i<n; i++)
{
if(st.empty())
left[i] = -1;
else if(heights[st.top()] >= heights[i])
{
while(!st.empty() && heights[st.top()] >= heights[i])
{
st.pop();
}
if(st.empty())
left[i] = -1;
else
left[i] = st.top();
}
else if(heights[st.top()] < heights[i])
left[i] = st.top();
st.push(i);
}
// print1d(left);
// right
vector<int> right(n);
stack<int> st1;
for(int i = n-1; i>=0; i--)
{
if(st1.empty())
right[i] = n;
else if(heights[st1.top()] >= heights[i])
{
while(!st1.empty() && heights[st1.top()] >= heights[i])
{
st1.pop();
}
if(st1.empty())
right[i] = n;
else
right[i] = st1.top();
}
else if(heights[st1.top()] < heights[i])
right[i] = st1.top();
st1.push(i);
}
// print1d(right);
// width
int maxwidth = INT_MIN;
for(int i = 0; i<n; i++)
{
maxwidth = max(maxwidth, (right[i] - left[i] -1 )* heights[i]);
}
return maxwidth;
}
};