Poison

11. Container With Most Water

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public int maxArea(int[] height) {
/*
核心思想是移动短板,从两侧向内移动时,距离会减小,那么我们要选择移动长板或者短板
如果移动长板,则两侧木板中的最小值只可能不变或者变小,即面积只会缩小(宽度减少了),所以我们不移动长板不会错过最大值
如果移动短板,则两侧木板中的最小值可能变大,即面积可能增大
*/
int maxArea = 0;
int i = 0, j = height.length - 1;
while (i < j) {
maxArea = Math.max(maxArea, Math.min(height[i], height[j]) * (j - i));
if (height[i] < height[j]) {
i++;
} else {
j--;
}
}

return maxArea;
}
}
Reference

11. Container With Most Water