-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathLargest_Rectangle_in_Histogram.cpp
More file actions
69 lines (62 loc) · 1.71 KB
/
Largest_Rectangle_in_Histogram.cpp
File metadata and controls
69 lines (62 loc) · 1.71 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
//https://leetcode.com/problems/largest-rectangle-in-histogram/
class Solution {
public:
int largestRectangleArea(vector<int>& heights)
{
int n = heights.size();
vector <int> prefix(n), suffix(n);
stack < int > s;
for(int i = 0; i < n; i++)
{
if(s.empty())
{
prefix[i] = 0;
s.push(i);
}
else if(heights[i] > heights[s.top()])
{
prefix[i] = s.top() + 1;
s.push(i);
}
else
{
while(!s.empty() && heights[i] <= heights[s.top()])
s.pop();
if(s.empty())
prefix[i] = 0;
else
prefix[i] = s.top() + 1;
s.push(i);
}
}
while(!s.empty())
s.pop();
for(int i = n-1; i >= 0; i--)
{
if(s.empty())
{
suffix[i] = n-1;
s.push(i);
}
else if(heights[i] > heights[s.top()])
{
suffix[i] = s.top() - 1;
s.push(i);
}
else
{
while(!s.empty() && heights[i] <= heights[s.top()])
s.pop();
if(s.empty())
suffix[i] = n-1;
else
suffix[i] = s.top() - 1;
s.push(i);
}
}
int largest = 0;
for(int i = 0; i < n; i++)
largest = max(largest, (suffix[i]-prefix[i]+1)*heights[i]);
return largest;
}
};