盛最多水的容器

Problem description

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.

Examples

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

Solution

  自己起初想以双指针从两头向中间逼近。但困惑于low、high的指针移动。我知道面积取决与最短板的长度。但是也还有宽度不是……..然后用了双层遍历,做是做出来了,但是特别耗时。参考网上代码,与我起初想法一致,向中间逼近,在指针移动时,采取移动最短指针,尽管面积 = 长度 * 宽度,但是面积取决于最短板,而且在移动过程中我们维护一个最大面积变量记录最大面积。可将宽度考虑其中。

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
 public int maxArea(int[] height) {
int maxArea = Integer.MIN_VALUE;
int low = 0, high = height.length - 1;
while (low < high) {
int area = Math.min(height[low], height[high]) * (high - low);
maxArea = Math.max(area, maxArea);
if (height[low] <= height[high]) {
low++;
} else {
high--;
}
}
return maxArea;
}
文章目录
  1. 1. Problem description
    1. 1.1. 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.
  2. 2. Examples
  3. 3. Solution
  4. 4. Code
|