题目链接:https://leetcode.com/problems/container-with-most-water/#/description
题目要求:在n条不同高度的柱子中选择两个柱子,(每两个相邻柱子之间等间隔)使其构成的容器装水最多。
思路:从左右两侧向中间靠拢(因为如果选择左右两侧的两个柱子,宽度已经最大,要想扩大容积...其实是面积...只能考虑增大高度)。首先选取的两个柱子是最左边和最右边的两个,然后较矮的那个柱子所在的一侧,向对面移动。比如,如果左侧的柱子比右侧的柱子矮,则左指针向右移动。
Java代码如下:
public class Solution {
public int maxArea(int[] height) {
int left = 0;
int right = height.length - 1;
int maxArea = 0;
while (left < right) {
maxArea = Math.max(maxArea, Math.min(height[left], height[right]) * (right - left));
// 如果左边的柱子高,右指针向左移动
if (height[left] > height[right]) {
right--;
} else {
// 如果右边的柱子高,左指针向右移动
left++;
}
}
return maxArea;
}
}