题目链接:https://leetcode-cn.com/problems/trapping-rain-water/
题目描述:
题解:
class Solution {
public:
int trap(vector<int>& height) {
vector<int> maxLeft(height.size(), 0);
vector<int> maxRight(height.size(), 0);
//记录每个柱子左边的最大高度
maxLeft[0] = height[0];
for(int i = 1; i < height.size(); i++)
{
maxLeft[i] = max(height[i], maxLeft[i - 1]);
}
//记录每个柱子右边的最大高度
maxRight[height.size() - 1] = height[height.size() - 1];
for(int i = height.size() - 2; i >= 0; i--)
{
maxRight[i] = max(height[i], maxRight[i + 1]);
}
int sum = 0;
for(int i = 0; i < height.size(); i++)
{
int count = min(maxLeft[i], maxRight[i]) - height[i];
if(count > 0)
sum += count;
}
return sum;
}
};