Trapping Rain Water - Implementation

Here is the implementation:

function trap(height):
    left = 0
    right = height.length - 1
    leftMax = 0
    rightMax = 0
    water = 0

    while left < right:
        if height[left] < height[right]:
            if height[left] >= leftMax:
                leftMax = height[left]
            else:
                water += leftMax - height[left]
            left += 1
        else:
            if height[right] >= rightMax:
                rightMax = height[right]
            else:
                water += rightMax - height[right]
            right -= 1

    return water

O(n)O(n) time, O(1)O(1) space (excluding input). Each position visited once.