-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLargestRectangleInHistogram.cpp
More file actions
60 lines (56 loc) · 1.6 KB
/
LargestRectangleInHistogram.cpp
File metadata and controls
60 lines (56 loc) · 1.6 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
54
55
56
57
58
59
60
/***
* 分块计算
* 每次找到波峰i
* 遍历i之前的矩形面积
* 时间复杂度O(n^2)
***/
/***
class Solution {
public:
int largestRectangleArea(vector<int> &height) {
int maxRA = 0;
const int n = height.size();
for (int i = 0; i < n; ++i)
{
if ((i < n-1) && (height[i] <= height[i+1])) // not last || not local highest
continue;
int minh = height[i];
for (int j = i; j >= 0; --j) // foreach the start of rectangle
{
minh = std::min(minh, height[j]);
maxRA = std::max(maxRA, (i-j+1) * minh);
}
}
return maxRA;
}
};
***/
/***
* 法2:用辅助栈,同样是找波峰
* 栈中维护的是递增的height对应的索引
* 当前元素小于栈顶元素时,入栈
* 否则,合并现有栈,直到栈顶元素小于当前元素
* 为方便最后一段的处理,在height的末尾压入0
***/
class Solution {
public:
int largestRectangleArea(vector<int> &height) {
int maxRA = 0;
height.push_back(0); // ensure every segment will be processed
const int n = height.size();
stack<int> shi; // height index
for (int i = 0; i < n; )
{
if (shi.empty() || (height[i] >= height[shi.top()]))
shi.push(i++);
else
{
int minhi = shi.top();
shi.pop();
int width = shi.empty() ? i : (i - shi.top() - 1); // if stack is empty, width is equal to i
maxRA = std::max(maxRA, height[minhi] * width);
}
}
return maxRA;
}
};