LeedCode42- catch rain

Catch rain

Question:
Given n non-negative integers representing the height map of each column with a width of 1, calculate how much rain water can be received by the columns arranged in this way.


The above is the height map represented by the array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain (blue Part represents rain)
Enter:

输入: [0,1,0,2,1,0,1,3,2,1,2,1]
输出: 6

Output:

9

Problem-solving idea:
How much water can be multiplied by each position depends on the smaller value of the maximum height leftMaxHeight on the left of the current position and the maximum height rightMaxHeight on the right minus the current height. If it is violent, the complexity is o(n 2 ). Here we can record the maximum value on the left side and the maximum value on the right side of each position flexibly in advance, so that the time complexity is reduced to o(n) and the space complexity is o (n).

// 每一个位置能乘多少水取决于,当前位置左边的最大高度leftMaxHeight和右边的最大高度rightMaxHeight的较小值减去当前高度
    public static int trap(int[] height) {
    
    
        if (null == height || 0 == height.length) {
    
    
            return 0;
        }

        int count = 0;

        final int size = height.length;

        // 记录一下当前位置左边的最大值
        int[] dpLeft = new int[size];
        // 记录一下当前位置右边的最大值
        int[] dpRight = new int[size];



        for(int i = 1 ; i < size ; i++ ){
    
    
            dpLeft[i] = Math.max(dpLeft[i-1] , height[i-1]);
        }


        for(int i = size-2 ; i > 0 ; i--){
    
    
            dpRight[i] = Math.max(dpRight[i+1] , height[i+1]);
        }

        for(int i = 1; i < size-1;i++){
    
    
            count += Math.max(Math.min(dpLeft[i] , dpRight[i]) - height[i] , 0);
        }

        return count;
    }

Guess you like

Origin blog.csdn.net/qq_37129433/article/details/104203461