leetcode 11 Container With Most Water 盛最多水的容器

描述

You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]).

Find two lines that together with the x-axis form a container, such that the container contains the most water.

Return the maximum amount of water a container can store.

Notice that you may not slant the container.

Example 1:

Input: height = [1,8,6,2,5,4,8,3,7]
Output: 49
Explanation: 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.
Example 2:

Input: height = [1,1]
Output: 1

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/container-with-most-water
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

题解

/**
 * 接雨水
 * 思路是:双指针,只移动短板
 * 因为移动长板,面积只会变得更小:
 *      当遇到更短的板子,面积变小
 *      当遇到更长的板子,面积仍然变小(因为容器面积取决于短板,长板变长没有用)
 *      当遇到长度不变的板子,面积还是变小,因为每次移动之后长-1
 * 因此,移动短板有可能使得面积变大或变小。 所以选择改变短板,才有可能使面积变大
 * @param {number[]} height
 * @return {number}
 */
var maxArea = function (height) {
    if (height.length < 3) return getArea(0, 1, height)
    let maxArea = 0
    let left = 0, right = height.length - 1
    while (left < right) {
        maxArea = height[left] < height[right] ? Math.max(getArea(left--, right, height), maxArea) : Math.max(getArea(left, right--, height), maxArea)
    }
    return maxArea
};

const getArea = (left, right, arr) => (right - left) * Math.min(arr[left], arr[right])
posted @ 2022-07-22 16:44  IslandZzzz  阅读(29)  评论(0编辑  收藏  举报