Hard

class Solution {
public:
    int trap(vector<int>& height) {
        if(height.size()<=2)return 0;

        int l=0,r=height.size()-1;

        int leftMost=height[l],rightMost=height[r];

        int total=0;
        while(l<=r)
        {
            if(leftMost<rightMost)
            {
                int cur=min(leftMost,rightMost)-height[l];
                total+=max(cur,0);
                leftMost=max(leftMost,height[l++]);
            }
            else
            {
                int cur=min(leftMost,rightMost)-height[r];
                total+=max(cur,0);
                rightMost=max(rightMost,height[r--]);
            }
        }

        return total;
    }
};

results matching ""

    No results matching ""