【Leetcode】11. Container With Most Water 数列中选两个值使得中间的面积最大

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
    原文地址: https://segmentfault.com/a/1190000007275611
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞