42. Trapping Rain Water (1)

Link

Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.

The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for contributing this image!

Example:

Input: [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6

Solution

求區間問題,透過兩個index來左右夾。

class Solution {
    public int trap(int[] height) {
        int len = height.length;
        int left =0, right = len -1;
        int maxLeft = 0, maxRight = 0;
        int ans = 0;
        while(right > left){
            maxLeft = Math.max(maxLeft, height[left]);
            maxRight = Math.max(maxRight, height[right]);
            if(maxRight > maxLeft)
            {
                //表示右邊有更高的bar,所以這次的左側的高低差
                //(maxLeft - height[left])會列入
                ans += maxLeft - height[left];
                left++;
            }
            else{
                //表示左邊有更高的bar,所以這次的右側的高低差
                //(maxRight - height[right])會列入
                ans += maxRight - height[right];
                right--;
            }
        }
        return ans; 

    }
    
}

Last updated

Was this helpful?