11. Container With Most Water

题目

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.

11. Container With Most Water
Example:

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

我的思路

使用双指针,一个从头一个从尾,但是具体怎么控制指针的移动?谁大移动谁?有点想法,但是很模糊

解答

感觉已经跟答案的想法很接近了!其实自己再多梳理一下就能做出来了
这里的思想是,因为往内移动,长是越来越短的,所以需要移动指针去寻找更高的地方

public class Solution {
    public int maxArea(int[] height) {
        int maxarea = 0, l = 0, r = height.length - 1;
        while (l < r) {
            maxarea = Math.max(maxarea, Math.min(height[l], height[r]) * (r - l));
            if (height[l] < height[r])
                l++;
            else
                r--;
        }
        return maxarea;
    }
}