Skip to content

Latest commit

 

History

History
24 lines (22 loc) · 585 Bytes

042.md

File metadata and controls

24 lines (22 loc) · 585 Bytes

42. Trapping Rain Water

Solution 1 (O(n))

class Solution {
    public int trap(int[] height) {
        int left = 0, right = height.length - 1;
        int ans = 0;
        while (left < right) {
            int t = Math.min(height[left], height[right]);
            while (height[left] <= t && left < right) {
                ans += t - height[left];
                left++;
            }
            while (height[right] <= t && left < right) {
                ans += t - height[right];
                right--;
            }
        }
        return ans;
    }
}