42. Trapping Rain Water
class Solution {
public:
    int trap(vector<int>& height) {
        int size = height.size(), max = -1, ind;
        for(int i = 0; i < size; i++){
            if(max <= height[i]){
                max = height[i];
                ind = i;
            }
        }
        int temp = -1;
        for(int i = 0; i < ind; i++){
           if(height[i] > temp) temp = height[i];
            height[i] = temp - height[i];
        }
        temp = -1;
        for(int i = size - 1; i >= ind; i--){
           if(height[i] > temp) temp = height[i];
            height[i] = temp - height[i];
        }
        int sum = 0;
        for(auto it : height) sum += it;
        return sum;
    }
};
Comments (0)