1. 题目

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.

2. 思路

从最两头向中间步进。当计算[i,j]范围后,下一步推进i,j小的那一个。记录下每次的容量,选出最大的。
cont(i, j) = min{len(i), len(j)}*(j - i);
if len(i) < len(j), 则可知已i为起点的情况下,如果推进j一定比当前的小。且>j的坐标的len一定比len j小,因为每一步的推进min(len i, len j)都是非递减的。

3. 代码

耗时:26ms

class Solution {
public:
    int maxArea(vector<int>& height) {
        int cap = 0;
        int left = 0;
        int right = height.size() - 1;
        while (left < right) {
            int cur = (right - left) * (height[left] < height[right] ? height[left] : height[right]);
            if (cur > cap) {
                cap = cur;
            }
            if (height[left] < height[right]) {
                left++;
            } else {
                right--;
            }
        }
        return cap;   
    }
};

knzeus
72 声望28 粉丝

行万里路,读万卷书