Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

11. 盛最多水的容器 #7

Open
webVueBlog opened this issue Aug 30, 2022 · 0 comments
Open

11. 盛最多水的容器 #7

webVueBlog opened this issue Aug 30, 2022 · 0 comments

Comments

@webVueBlog
Copy link
Owner

11. 盛最多水的容器

Description

Difficulty: 中等

Related Topics: 贪心, 数组, 双指针

给定一个长度为 n 的整数数组 height 。有 n 条垂线,第 i 条线的两个端点是 (i, 0) 和 (i, height[i]) 。

找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。

返回容器可以储存的最大水量。

**说明:**你不能倾斜容器。

示例 1:

输入:[1,8,6,2,5,4,8,3,7]
输出:49 
解释:图中垂直线代表输入数组 [1,8,6,2,5,4,8,3,7]。在此情况下,容器能够容纳水(表示为蓝色部分)的最大值为 49。

示例 2:

输入:height = [1,1]
输出:1

提示:

  • n == height.length
  • 2 <= n <= 105
  • 0 <= height[i] <= 104

Solution

Language: JavaScript

/**
 * @param {number[]} height
 * @return {number}
 */
var maxArea = function(height) {
    let [l, r, ans] = [0, height.length - 1, 0]

    while (l < r) {
        let [lh, lr] = [height[l], height[r]]
        ans = Math.max(ans, Math.min(lh, lr) * (r - l))

        lh < lr ? l++ : r--
    }

    return ans
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant