容器盛水问题NC128

/**
 * max water
 * @param arr int整型一维数组 the array
 * @return long长整型
 */
function maxWater( arr ) {
    
    
    // write code here
    if(!arr) return;
    let val = 0;
    let left = 0, right = arr.length -1;
    let leftMax = 0, rightMax = 0;
    while(left < right){
    
    
        leftMax = Math.max(arr[left],leftMax);
        rightMax = Math.max(arr[right], rightMax);
        if(leftMax <= rightMax){
    
    
            val += leftMax - arr[left];
            left++
        }else{
    
    
            val += rightMax - arr[right];
            right--
        }
    }
    return val
}
module.exports = {
    
    
    maxWater : maxWater
};

猜你喜欢

转载自blog.csdn.net/weixin_45284354/article/details/113867329