代码随想录day49 42. 接雨水 84. 柱状图中最大的矩形
代码随想录
class Solution {
public:
int trap(vector<int>& height) {
int size = height.size();
int result = 0;
stack<int> st;
st.push(0);
for (int i = 1; i < size; i++) {
while (!st.empty() && height[i] > height[st.top()]) {
int mid = st.top();
st.pop();
if (!st.empty()) {
int left = st.top();
result += (min(height[i], height[left]) - height[mid]) * (i - left - 1);
}
}
st.push(i);
}
return result;
}
};
代码随想录
class Solution {
public:
int largestRectangleArea(vector<int>& heights) {
heights.insert(heights.begin(), 0);
heights.push_back(0);
int size = heights.size();
int result = 0;
stack<int> st;
st.push(0);
for (int i = 1; i < size; i++) {
while (heights[i] < heights[st.top()]) {
int mid = st.top();
st.pop();
int tmp = heights[mid] * (i - st.top() - 1);
result = result > tmp ? result : tmp;
}
st.push(i);
}
return result;
}
};