My easy understanding cpp code


  • 0
    C
    class Solution {
    public:
        int trap(vector<int>& height) 
        {
            if(!height.size()) return 0;
            
            int l = 0, r = height.size()-1;
            int secHighest = 0;
            int area = 0;
            
            while(l < r)
            {
                if(height[l] < height[r])
                {
                    secHighest = std::max(secHighest, height[l]);
                    area += secHighest - height[l];
                    l++;
                }
                else
                {
                    secHighest = std::max(secHighest, height[r]);
                    area += secHighest - height[r];
                    r--;
                }
            }
            
            return area;
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.