题目

Given n non-negative integers 0011. Container With Most Water (M) - 图1 , where each represents a point at coordinate 0011. Container With Most Water (M) - 图2. n vertical lines are drawn such that the two endpoints of line i is at 0011. Container With Most Water (M) - 图3 and 0011. Container With Most Water (M) - 图4. 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.

image.png

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:

  1. Input: [1,8,6,2,5,4,8,3,7]
  2. Output: 49

题意

给出n个坐标点 0011. Container With Most Water (M) - 图6 ,每个坐标点与点 0011. Container With Most Water (M) - 图7 构成一条直线,任选两条直线,与x轴构成一个盛水的容器,求这个容器的最大容积。

思路

暴力法0011. Container With Most Water (M) - 图8

Two Pointers - 0011. Container With Most Water (M) - 图9 : 设两指针分别指向数组的左右两端,计算容积并更新最大容积,移动高度较短的指针进行下次循环。证明:影响容器容积的因素有两个,即底边长度和较短边高度,对于高度较短的一方,它已经达到了能够构成的最大容积(因为底边长度已经是最大),只有更换较短边才有可能抵消缩短底边长度带来的影响。
具体证明方法:过冰峰 - container-with-most-water(最大蓄水问题)


代码实现

Java

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

JavaScript

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