-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathlargest_rectangle_in_histogram.cpp
More file actions
48 lines (40 loc) · 1.05 KB
/
largest_rectangle_in_histogram.cpp
File metadata and controls
48 lines (40 loc) · 1.05 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
class Solution {
public:
int largestRectangleArea(vector<int> &height) {
int size = height.size();
if (0 == size) {
return 0;
}
int result = INT_MIN;
int index;
stack<int> bars;
for (int i = 0; i < size; ++i) {
if (!bars.empty()) {
// 如果堆栈顶部的元素比当前的高度高,弹出并计算可能的面积
while ((!bars.empty()) && (height[bars.top()] > height[i])) {
index = bars.top();
bars.pop();
if (bars.empty()) {
result = max(result, i * height[index]);
}
else {
result = max(result, (i - bars.top() - 1) * height[index]);
}
}
}
// 前面的元素必须小于等于当前元素
bars.push(i);
}
while (!bars.empty()) {
index = bars.top();
bars.pop();
if (bars.empty()) {
result = max(result, size * height[index]);
}
else {
result = max(result, (size - bars.top() - 1) * height[index]);
}
}
return result;
}
};