Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add solutions to lc problem: No.039 #647

Merged
merged 1 commit into from
Dec 30, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions lcof2/剑指 Offer II 039. 直方图最大矩形面积/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,34 @@

```

### **C++**

我们遍历每个柱体,若当前的柱体高度大于等于栈顶柱体的高度,就直接将当前柱体入栈,否则若当前的柱体高度小于栈顶柱体的高度,说明当前栈顶柱体找到了右边的第一个小于自身的柱体,那么就可以将栈顶柱体出栈来计算以其为高的矩形的面积了。

```cpp
class Solution {
public:
int largestRectangleArea(vector<int>& heights) {
int maxarea = 0;
stack<int> s;
heights.insert(heights.begin(), 0);
heights.push_back(0);

for (int i = 0; i < heights.size(); i++) {
while (!s.empty() && heights[i] < heights[s.top()]) {
int h = heights[s.top()];
s.pop();
maxarea = max(maxarea, h * (i - s.top() - 1));
}

s.push(i);
}

return maxarea;
}
};
```

### **...**

```
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
class Solution {
public:
int largestRectangleArea(vector<int>& heights) {
int maxarea = 0;
stack<int> s;
heights.insert(heights.begin(), 0);
heights.push_back(0);

for (int i = 0; i < heights.size(); i++) {
while (!s.empty() && heights[i] < heights[s.top()]) {
int h = heights[s.top()];
s.pop();
maxarea = max(maxarea, h * (i - s.top() - 1));
}

s.push(i);
}

return maxarea;
}
};