LeetCode-11-Container With Most Water

LeetCode-11-Container With Most Water

一、问题描述

  给定一个数组,在数组中找到两个位置,使他们的高和底形成的容器装最多的水。

  例子:数组为{ 1 ,8 ,6 ,2, 5 ,4 ,8, 3 ,7 },若选取头和尾两个点,他们装的水为如下图

二、问题解决

  从两边想中间逼近,若左边点高度小于右边,则左边的点右移,否则右边的点左移。以例子中的数组为例,过程如下:

 

  代码如下:

int maxArea(vector<int>& height) {
    int result = 0;
    int i = 0; int j = height.size() - 1;
    while (i < j) {
        int current = min(height.at(i), height.at(j));
        if (result < current*(j - i))
            result = current*(j - i);
        if (height[i] <= height[j])
            i++;
        else
            j--;
    }
    return result;
}

int main()
{
    vector<int> nums = { 1 ,8 ,6 ,2, 5 ,4 ,8, 3 ,7 };
    cout << maxArea(nums) << endl;

    system("pause");
    return 0;
}
原文地址:https://www.cnblogs.com/likaiming/p/8270401.html