-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlargest-rectangle-in-histogram.cpp
42 lines (42 loc) · 1.23 KB
/
largest-rectangle-in-histogram.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
class Solution {
public:
vector<int> getNSL(vector<int>& heights) {
vector<int> NSL(heights.size());
stack<int> s;
for (int i = 0; i < heights.size(); i++) {
while (!s.empty() && heights[i] <= heights[s.top()])
s.pop();
if (s.empty())
NSL[i] = -1;
else
NSL[i] = s.top();
s.push(i);
}
return NSL;
}
vector<int> getNSR(vector<int>& heights) {
vector<int> NSR(heights.size());
stack<int> s;
for (int i = heights.size() - 1; i >= 0; --i) {
while (!s.empty() && heights[i] <= heights[s.top()])
s.pop();
if (s.empty())
NSR[i] = heights.size();
else
NSR[i] = s.top();
s.push(i);
}
return NSR;
}
int largestRectangleArea(vector<int>& heights) {
if (heights.size() == 1)
return heights[0];
vector<int> NSR = getNSR(heights);
vector<int> NSL = getNSL(heights);
int maxi = 0;
for (int i = 0; i < heights.size(); i++) {
maxi = max(maxi, (NSR[i] - NSL[i] - 1) * heights[i]);
}
return maxi;
}
};