Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) 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.
Example:
Input: [1,8,6,2,5,4,8,3,7] Output: 49
盛最多水的容器。
给你 n 个非负整数 a1,a2,...,an,每个数代表坐标中的一个点 (i, ai) 。在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (i, ai) 和 (i, 0) 。找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。
说明:你不能倾斜容器。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/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 };