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.

解题思想

关键的思路在于:对于任意的容器,它的容积取决于最短的那个板子。
采用双指针的思想,从首尾往中间扫描数组,扫描过程中,只移动短板端的指针,因为容器的容积取决于短板,只有在改变短板的时候才有可能产生新的最大值。

解题代码

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

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

int main()
{
    Solution solution;
    vector<int> height = {7, 5, 6, 9};
    cout << solution.maxArea(height) << endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/u013507678/article/details/80482729