water storage algorithm

water storage

Given an array, regarded as a container, find the volume of water that can be stored

Arr = {3,1,3} à can store 2

Arr = {1,2,3,4,2,1} à can store 1

 

Algorithm Analysis:

  1. In terms of a single element, the volume of water at the top of it is the value of the smallest item in the maximum set on the left and right sides minus the height of its position, and it can be calculated by calculating all its elements.
  2. Set the maximum value on the left and right sides, traverse from the beginning to the end, and set leftMax and rightMax. If leftMax<rightMax, it indicates whether the element on the right can store water and how much depends on the value on the left (the barrel principle), and vice versa

 

    public int getWater1(int[] arr){
        int val = 0;
        int leftMax = arr[0];
        int rightMax = arr[arr.length-1];
        int leftIndex = 1;
        int rightIndex = arr.length-2;
        while(leftIndex<=rightIndex){    //此处需要注意是 <=
            if(leftMax<rightMax){
                val += Math.max(0, leftMax-arr[rightIndex]);
                rightMax = Math.max(rightMax, arr[rightIndex--]);
            }else{
                val += Math.max(0, rightMax-arr[leftIndex]);
                leftMax = Math.max(leftMax, arr[leftIndex++]); 
            }
        }
        return val;
    }

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325264654&siteId=291194637