-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLargest Rectangle in Histogram.cpp
47 lines (44 loc) · 1.31 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
43
44
45
46
47
#include <iostream>
#include <vector>
#include <stack>
using namespace std;
class Solution {
public:
int largestRectangleArea(vector<int> &height)
{
if (height.size() == 0) return 0;
stack<int> helper;
int res = 0;
height.push_back(0);
for (int i=0; i<height.size(); i++){
if (helper.empty() || height[helper.top()] <= height[i] ) {
helper.push(i);
}
else{
while(!helper.empty() && height[helper.top()] > height[i]){
int tmp = helper.top();
cout << height[tmp] << endl;
helper.pop();
if (!helper.empty()){
//前一点不一定与当前点紧挨着,因此之前先pop,然后再top。
int pre = helper.top();
res = max(res, height[tmp] * (i - pre - 1));
}
else {
res = max(res, height[tmp] * (i));
}
cout << res << endl;
}
helper.push(i);
}
}
return res;
}
};
int main() {
int arr[] = {1, 2, 5, 3};
std::vector<int> v(arr, arr + 4);
Solution s;
cout << s.largestRectangleArea(v) << endl;
return 0;
}