Java O(n) two pointer, and a clean and short one


  • 0
    Z

    same as other two pointer solutions, just try to make it clear and short

        public int trap(int[] height) {
            int l = 0, u = height.length - 1;
            int water = 0, dam = 0;
            while(l < u) {
                int min = height[l] < height[u]? height[l++]: height[u--];
                water += Math.max(dam - min, 0);
                dam = Math.max(dam, min);
            }
    
            return water;
        }
    

Log in to reply
 

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