算法题解

1. Container With Most Water
Given n non-negative integers a1a2, ..., an , where each represents a point at coordinate (iai). n vertical lines are drawn such that the two endpoints of line i is at (iai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.

Note: You may not slant the container and n is at least 2.

The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.

解析:这个问题可以看成在底和高之间不断取舍的问题。先取最长底,算出一个容积。然后去不断尝试用底的损失去换取一个可以带来更大容积的高。不断放弃无法带来更大容积的高,最终确定最优解。

/**
 * @param {number[]} height
 * @return {number}
 */
var maxArea = function(height) {
    if (!height || height.length <= 1) return 0;
    
    // 双指针来进行优化
    // 时间复杂度是O(n)
    let leftPos = 0;
    let rightPos = height.length - 1;
    let max = 0;
    while(leftPos < rightPos) {
        
        const currentArea = Math.abs(leftPos - rightPos) * Math.min(height[leftPos] , height[rightPos]);
        if (currentArea > max) {
            max = currentArea;
        }
        // 更新小的
        if (height[leftPos] < height[rightPos]) {
            leftPos++;
        } else { // 如果相等就随便了
            rightPos--;
        }
    }

    return max;
};
原文地址:https://www.cnblogs.com/wllhq/p/12070102.html