[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

Constraints:

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

盛最多水的容器。

给定一个长度为 n 的整数数组 height 。有 n 条垂线,第 i 条线的两个端点是 (i, 0) 和 (i, height[i]) 。
找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。
返回容器可以储存的最大水量。
说明:你不能倾斜容器。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/container-with-most-water
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

存储水量 = 宽度 * 高度 = (right - left) * Math.min(height[left], height[right])

时间O(n)

空间O(1)

Java实现

 1 class Solution {
 2     public int maxArea(int[] height) {
 3         int res = 0;
 4         int left = 0;
 5         int right = height.length - 1;
 6         while (left < right) {
 7             res = Math.max(res, Math.min(height[left], height[right]) * (right - left));
 8             if (height[left] < height[right]) {
 9                 left++;
10             } else {
11                 right--;
12             }
13         }
14         return res;
15     }
16 }

 

JavaScript实现

 1 /**
 2  * @param {number[]} height
 3  * @return {number}
 4  */
 5 var maxArea = function (height) {
 6     let res = 0;
 7     let left = 0;
 8     let right = height.length - 1;
 9     while (left < right) {
10         res = Math.max(res, Math.min(height[left], height[right]) * (right - left));
11         if (height[left] < height[right]) {
12             left++;
13         } else {
14             right--;
15         }
16     }
17     return res;
18 };

 

LeetCode 题目总结

posted @ 2019-11-02 12:41  CNoodle  阅读(490)  评论(0)    收藏  举报