My c++ code O(1) space and easy to understand!


  • 0
    P

    class Solution {
    public:
    int trap(vector<int>& height) {
    if(height.size()<3) return 0;
    int l = 0;
    int r = height.size()-1;
    int l_max = height[l];
    int r_max = height[r];
    int sum=0;
    while(l<r){
    if(height[l]<height[r]){
    l++;
    if(height[l]<l_max){
    sum+=l_max-height[l];
    }else{
    l_max=height[l];
    }
    }
    else{
    r--;
    if(height[r]<r_max){
    sum+=r_max-height[r];
    }else{
    r_max=height[r];
    }
    }
    }
    return sum;
    }
    };


Log in to reply
 

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