-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlargestRecInHis.cpp
61 lines (60 loc) · 1.38 KB
/
largestRecInHis.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
class Solution
{
public:
int largestRectangleArea(vector<int> &heights)
{
stack<int> st;
int n = heights.size();
if (n == 1)
{
return heights[0];
}
int left[n], right[n], area = 0, mxa = 0;
left[0] = 0;
right[n - 1] = n - 1;
st.push(0);
for (int i = 1; i < n; i++)
{
while (!st.empty() and heights[st.top()] >= heights[i])
{
st.pop();
}
if (!st.empty())
{
left[i] = st.top() + 1;
}
else
{
left[i] = 0;
}
st.push(i);
}
while (!st.empty())
{
st.pop();
}
st.push(n - 1);
for (int i = n - 2; i >= 0; i--)
{
while (!st.empty() and heights[st.top()] >= heights[i])
{
st.pop();
}
if (!st.empty())
{
right[i] = st.top() - 1;
}
else
{
right[i] = n - 1;
}
st.push(i);
}
for (int i = 0; i < n; i++)
{
area = (right[i] - left[i] + 1) * heights[i];
mxa = max(area, mxa);
}
return mxa;
}
};