水容器问题

给定一个整形数组arr,已知其中所有的值都是非负的,将这个数组看作一个容器,请返回容器能装多少水。

[3,1,2,5,2,4]

输出

5
func maxWater( arr []int ) int64 {
    // write code here
    if len(arr) <3{return 0}
    water := 0
    i,j := 0,len(arr)-1
    maxLeft := arr[i]; //桶左边的长度
    maxRight := arr[j]; // 桶右边的长度
         // 盛水总量
        for (i < j){
        	// 较低边为左边
            if(maxLeft < maxRight){
                i++;
                // 当前位置i小于大于较低边,更新较低边的值,小于装水
                if(arr[i] > maxLeft){
                    maxLeft = arr[i];
                }else{
                    water += maxLeft - arr[i];
                }
            }else{
            	// 较低边为右边
                j--;
                 // 当前位置i小于大于较低边,更新较低边的值,小于装水
                if(arr[j] > maxRight){
                    maxRight = arr[j];
                }else{
                    water += maxRight - arr[j];
                }
            }
        }
    return int64(water)
}

  

原文地址:https://www.cnblogs.com/lvpengbo/p/14470691.html