[LeetCode] 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.


</br>

Solution

As we know, the volume of the water is determined by the height and the width of the container, and height is restricted by the shorter line of the container.

Suppose we start by two pointer at each side of the array, if we want to expand the area, we should not move the longer line as the height is restricted by the shorter one.

Instead, we can move the shorter line to increase the height. Since we start from two side of the array, we begin with the maximum width so we do not have to worry about the potential area increase when moving line inwards.

Consider this: we start with

[most_left, most_right]  
    The width is (n-1) - 0
    //The biggest width can be achieved

So, if we move the longer line of these two, not only will we lose the width, but also gain no increase in height. Hence, we can ignore this movement.

And there is nothing tricky left, the code is self-explained.

Java

public class Solution {
    public int maxArea(int[] height) {
        
        int min_height = 0, area = 0;
        int i = 0, j = height.length - 1;
        
        while (i < height.length && j >= 0){
        
                
                if (height[j] > height[i]){
                    area = Math.max(area, height[i] * (j-i));
                    i++;
                }
                else {
                    area = Math.max(area, height[j] * (j-i));
                    j--;
                }
            
            
        }
        return area;
    }
}

</br>

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 今天和客户谈了一下,她说了很多,尤其是关于钱方面,没有钱,在最关键的时候,是会气死自己的,有好几次,都会很气,但是...
    海豚的世界_0820阅读 476评论 0 0
  • 记得那天去的时候,大家脸上都面无表情,平平淡淡,但我知道还是有些许激动的。终于可以参观到731部队的遗址,在控诉侵...
    欧几得里阅读 145评论 1 5
  • 我见过的手数不胜数,大手,小手,皮肤细腻的手,皮肤粗糙的手,温暖的手,冰凉的手........ 妈妈的手是灵巧的手...
    辣妈赵十八阅读 199评论 2 2