def trap(height):
l,r=0,len(height)-1
lmax=rmax=water=0
while l<r:
if height[l]<=height[r]:
if height[l]>=lmax: lmax=height[l]
else: water+=lmax-height[l]
l+=1
else:
if height[r]>=rmax: rmax=height[r]
else: water+=rmax-height[r]
r-=1
return water
public int trap(int[] height){
int l=0,r=height.length-1,lmax=0,rmax=0,water=0;
while(l<r){
if(height[l]<=height[r]){
if(height[l]>=lmax) lmax=height[l];
else water+=lmax-height[l];
l++;
} else {
if(height[r]>=rmax) rmax=height[r];
else water+=rmax-height[r];
r--;
}
} return water;
}
O(1) space. Python chain assign. Algorithm identical.
def trap(height):
l,r=0,len(height)-1
lmax=rmax=water=0
while l<r:
if height[l]<=height[r]:
if height[l]>=lmax: lmax=height[l]
else: water+=lmax-height[l]
l+=1
else:
if height[r]>=rmax: rmax=height[r]
else: water+=rmax-height[r]
r-=1
return water
public int trap(int[] height){
int l=0,r=height.length-1,lmax=0,rmax=0,water=0;
while(l<r){
if(height[l]<=height[r]){
if(height[l]>=lmax) lmax=height[l];
else water+=lmax-height[l];
l++;
} else {
if(height[r]>=rmax) rmax=height[r];
else water+=rmax-height[r];
r--;
}
} return water;
}
1. Process shorter side 2. Accumulate water 3. Move inward