Skip to content

Commit 56ab781

Browse files
authored
feat: add solutions to lcof2 problem: No.039 (doocs#647)
1 parent dee5cd0 commit 56ab781

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed

lcof2/剑指 Offer II 039. 直方图最大矩形面积/README.md

+28
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,34 @@
6363

6464
```
6565

66+
### **C++**
67+
68+
我们遍历每个柱体,若当前的柱体高度大于等于栈顶柱体的高度,就直接将当前柱体入栈,否则若当前的柱体高度小于栈顶柱体的高度,说明当前栈顶柱体找到了右边的第一个小于自身的柱体,那么就可以将栈顶柱体出栈来计算以其为高的矩形的面积了。
69+
70+
```cpp
71+
class Solution {
72+
public:
73+
int largestRectangleArea(vector<int>& heights) {
74+
int maxarea = 0;
75+
stack<int> s;
76+
heights.insert(heights.begin(), 0);
77+
heights.push_back(0);
78+
79+
for (int i = 0; i < heights.size(); i++) {
80+
while (!s.empty() && heights[i] < heights[s.top()]) {
81+
int h = heights[s.top()];
82+
s.pop();
83+
maxarea = max(maxarea, h * (i - s.top() - 1));
84+
}
85+
86+
s.push(i);
87+
}
88+
89+
return maxarea;
90+
}
91+
};
92+
```
93+
6694
### **...**
6795

6896
```
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
class Solution {
2+
public:
3+
int largestRectangleArea(vector<int>& heights) {
4+
int maxarea = 0;
5+
stack<int> s;
6+
heights.insert(heights.begin(), 0);
7+
heights.push_back(0);
8+
9+
for (int i = 0; i < heights.size(); i++) {
10+
while (!s.empty() && heights[i] < heights[s.top()]) {
11+
int h = heights[s.top()];
12+
s.pop();
13+
maxarea = max(maxarea, h * (i - s.top() - 1));
14+
}
15+
16+
s.push(i);
17+
}
18+
19+
return maxarea;
20+
}
21+
};

0 commit comments

Comments
 (0)