-
Notifications
You must be signed in to change notification settings - Fork 0
/
largestRectangleArea_Hard.cc
72 lines (61 loc) · 1.69 KB
/
largestRectangleArea_Hard.cc
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
70
71
72
/**
* http://tech-queries.blogspot.com/2011/03/maximum-area-rectangle-in-histogram.html
*/
#include <iostream>
#include <vector>
#include <stack>
using namespace std;
class Solution {
public:
int largestRectangleArea(vector<int> &height) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int n = height.size();
stack<int> s;
int area[n]; // to store the longest width rectangle with height[i];
int t;
for (int i = 0; i < n; ++i) area[i] = 0;
for (int i = 0; i < n; i++) {
// find the first height that less than height[i], so that we can get the width of this rectangle
while(!s.empty()) {
if (height[i] <=height[s.top()])
s.pop();
else
break;
}
if (s.empty())
t = -1;
else
t = s.top();
area[i] = i - t - 1;
s.push(i);
}
while(!s.empty()) s.pop();
for (int i = n - 1; i >= 0; i--) {
// find the first height that less than height[i], so that we can get the width of this rectangle
while(!s.empty()) {
if (height[i] <=height[s.top()])
s.pop();
else
break;
}
if (s.empty())
t = n; // need to be n!!!
// cause if s is not empty s.top() is the leftest out of range, so t - i we do not +1, but if it empty we cannot use n - 1,
// cause we miss one there and we cannot simply change to t - i + 1, cause this will mess up the no empty case;
else
t = s.top();
area[i] += t - i - 1;
s.push(i);
}
int max = 0;
for (int i = 0; i < n; ++i) {
if ((height[i] * (area[i] + 1) > max ))
max = height[i] * (area[i] + 1);
}
return max;
}
};
int main(int argc, char **argv) {
return 0;
}