GuilinDev

Lc0011

05 August 2008

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.

The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.

Example:

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

题意和分析

跟42 Trapping Rain Water类似,略简单一点,只需要用双指针指向头尾,然后往中间走计算装雨水的面积即可,移动的办法是挪动较矮的线的index以防错过最大值,计算面积的方法是找到两条线中较矮的那条,乘以两条线的距离。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
    public int maxArea(int[] height) {
        int result = 0, left = 0, right = height.length - 1;

        while (left < right) {
            result = Math.max(result, Math.min(height[left], height[right]) * (right - left));

            //移动较矮的那条线的index
            if (height[left] < height[right]) {
                left++;
            } else { 
            // 如果两根柱子相等高度,移动任何一根都可以,因为长度变小了,就算当前柱子为最低,也不会跳过最大值
                right--;
            }
        }
        return result;
    }
}