-
Notifications
You must be signed in to change notification settings - Fork 1
/
LargestRectangleinHistogram.cpp
53 lines (51 loc) · 1.36 KB
/
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
/*
Given n non-negative integers representing the histogram's bar height where the width of each bar is 1,
find the area of largest rectangle in the histogram.
*/
class Solution {
public:
int largestRectangleArea(vector<int> &height) {
return largestRectangleArea_1(height);
}
int largestRectangleArea_1(vector<int> &height)
{
int len = height.size();
vector<int> left(len,0);
vector<int> right(len,len-1);
for(int i=1;i<len;i++)
{
if(height[i]>height[i-1])
left[i] = i;
else
{
int idx = i-1;
while(height[i]<=height[idx]&&idx>=0)
{
left[i] = left[idx];
idx = left[idx]-1;
}
}
}
for(int i=len-2;i>=0;i--)
{
if(height[i]>height[i+1])
right[i] = i;
else
{
int idx = i+1;
while(height[i]<=height[idx]&&idx<len)
{
right[i] = right[idx];
idx = right[idx]+1;
}
}
}
int result = 0;
for(int i=0;i<len;i++)
{
int area = height[i]*(right[i]-left[i]+1);
result = max(result,area);
}
return result;
}
};