LeetCode 11 盛水最多的容器

LeetCode 11 盛水最多的容器

🟡 中等

https://leetcode.cn/problems/container-with-most-water/description/

首先, 双指针法设置两个指针在数组的首尾,

  • 考虑指针移动的规则: 如果移动长的一边, 那么容器的高(依赖于短的一边)是不变的, 而底是在减小的, 所以到最后容器的体积不会增大. 因此要移动短的一边, 底虽然减小了, 但是高可能能找到更大的一个。
class Solution {

public:

    int maxArea(vector<int>& height) {

        int left = 0;

        int right = height.size()-1;

        int ans = 0;

        while(left<right){

            int h = min(height[left],height[right]);

            ans = max(ans,(right-left)*h);

            if(height[left]<height[right]){

                left++;

            }else{

                right--;

            }

        }

        return ans;

    }

};