Two pointer


  • 0
    F

    public int trap(int[] height) {
    int result = 0;
    int left = 0;
    int right = height.length - 1;

            if (left >= right) return result;
    
            int leftH = height[left];
            int rightH = height[right];
    
            while (left < right) {
                if (leftH < rightH) {
                    left++;
                    if (leftH > height[left]) {
                        result += leftH - height[left];
                    } else {
                        leftH = height[left];
                    }
                } else {
                    right--;
                    if (rightH > height[right]) {
                        result += rightH - height[right];
                    } else {
                        rightH = height[right];
                    }
                }
            }
    
            return result;
        }

Log in to reply
 

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