day41
接雨水
class Solution {
public:
int trap(vector
int ret = 0;
stack
st.push(0);
for(int i = 1; i < height.size(); ++i)
{
if(height[i] <= height[st.top()])
{
st.push(i);
}
else
{
while(!st.empty() && height[i] > height[st.top()])
{
int mid = st.top();
st.pop();
if(!st.empty())
{
int h = min(height[i], height[st.top()]) - height[mid];
int w = i- st.top() - 1;
ret += h * w;
}
}
st.push(i);
}
}
return ret;
}
};
柱状图中最大的矩形
class Solution {
public:
int largestRectangleArea(vector
int ret = 0;
heights.insert(heights.begin(), 0); // 数组头部加入元素0
heights.push_back(0); // 数组尾部加入元素0
stack
st.push(0);
for(int i = 1; i < heights.size(); ++i)
{
if(heights[i] >= heights[st.top()])
{
st.push(i);
}
else
{
while(!st.empty() && heights[i] < heights[st.top()])
{
int mid =st.top();
st.pop();
if(!st.empty())
{
ret = max(ret, heights[mid] * (i - st.top() - 1));
}
}
st.push(i);
}
}
return ret;
}
};