-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0084. Largest Rectangle in Histogram.cpp
More file actions
53 lines (49 loc) · 1.42 KB
/
Copy path0084. Largest Rectangle in Histogram.cpp
File metadata and controls
53 lines (49 loc) · 1.42 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
class Solution {
public:
int largestRectangleArea(vector<int> &heights) {
// init
int n = heights.size();
vector<int> left(n), right(n);
stack<int> s;
// get left indices
for (int i = 0; i < n; i++) {
// determine limiting left index
if (s.empty())
left[i] = 0;
else {
while (!s.empty() && heights[s.top()] >= heights[i])
s.pop();
if (s.empty())
left[i] = 0;
else
left[i] = s.top() + 1;
}
// add curr to stack
s.push(i);
}
// reset stack
while (!s.empty())
s.pop();
// get right indices
for (int i = n - 1; i >= 0; i--) {
// determine limiting right index
if (s.empty())
right[i] = n - 1;
else {
while (!s.empty() && heights[s.top()] >= heights[i])
s.pop();
if (s.empty())
right[i] = n - 1;
else
right[i] = s.top() - 1;
}
// add curr to stack
s.push(i);
}
// get answer and return
int ans = 0;
for (int i = 0; i < n; i++)
ans = max(ans, heights[i] * (right[i] - left[i] + 1));
return ans;
}
};