Skip to content

Commit d6a7ac3

Browse files
committed
Largest Rect in Histogram: stack, track last histogram that no lower than cur height.
1 parent 771d96d commit d6a7ac3

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
#include "../Header.h"
2+
3+
using namespace std;
4+
int largestRectangleArea(vector<int>& heights) {
5+
int maxArea = 0, sz = heights.size();
6+
stack<int> lastIndex;
7+
for (int i = 0; i < sz; i++) {
8+
while (!lastIndex.empty() && heights[lastIndex.top()] > heights[i]) {
9+
int l = lastIndex.top();
10+
lastIndex.pop();
11+
// w+1 代表的坐标是高度不小于当前高度的最左边的坐标
12+
// 栈空代表当前高度为目前为止的最低高度
13+
int w = lastIndex.empty() ? -1 : lastIndex.top();
14+
maxArea = max(maxArea, heights[l] * (i - (w + 1)));
15+
}
16+
lastIndex.push(i);
17+
}
18+
// 处理递增数列
19+
while (!lastIndex.empty()) {
20+
int l = lastIndex.top();
21+
lastIndex.pop();
22+
int w = lastIndex.empty() ? -1 : lastIndex.top();
23+
maxArea = max(maxArea, heights[l] * (sz - (w + 1)));
24+
}
25+
return maxArea;
26+
}
27+
int main(int argc, char const *argv[])
28+
{
29+
vector<int> v = genRandVector(10, 10);
30+
cout << "v = " << toString(v) << endl;
31+
cout << "largestRectangleArea(v) = " << largestRectangleArea(v) << endl;
32+
return 0;
33+
}

0 commit comments

Comments
 (0)