42. Trapping Rain Water
problem description
Input: [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6algorithm thought
code
class Solution {
public:
int trap(vector<int>& height) {
if(height.size()==0)
return 0;
int left=0;
int right=height.size()-1;
int leftmax=height[left];
int rightmax=height[right];
int res=0;
while(left<right){
// cout<<left<<'-'<<right<<' ';
if(height[left]<height[right]){
if(height[left]<=leftmax){
res+=leftmax-height[left++];
}else{
leftmax=height[left];
}
}else{
if(height[right]<=rightmax){
res+=rightmax-height[right--];
}else{
rightmax=height[right];
}
}
}
return res;
}
};algorithm thought
Last updated
