[LeetCode Hot Topic 100] [Double Pointers] The container that holds the most water

Given an integer array of length n height . There are n vertical lines, and the two endpoints of the i line are (i, 0) and (i, height[i]) .

Find two of the lines so that the container formed by them and the x axis can hold the most water.

Returns the maximum amount of water the container can store.

Note:You cannot tilt the container.

Example 1:

Input:[1,8,6,2,5,4,8,3,7]
Output: 49 
Explanation: The vertical lines in the figure represent the input array [1,8,6,2,5,4,8,3,7]. In this case, the maximum value of water (shown in blue) that the container can hold is 49. 

Example 2:

Import:height = [1,1]
Exit: 1

hint:

  • n == height.length
  • 2 <= n <= 105
  • 0 <= height[i] <= 104

answer 

The first idea when seeing this question is to find the maximum product with two layers of loops

class Solution {
public:
    int maxArea(vector<int>& height) {
        auto capacity=[&height](int begin,int end)->int{
            int h=height[begin]<height[end]?height[begin]:height[end];
            int width=end-begin;
            return h*width;
        };
        int max=0;
        for(int i=0;i<height.size()-1;i++){
            for(int j=i+1;j<height.size();j++){
                int c=capacity(i,j);
                max=max<c?c:max;
            }
        }
        return max;
    }
};

But it timed out

We change the two-layer loop into a one-layer loop, use the double pointer method, let left=0, right=n-1, and calculate the capacity starting from the wooden boards on both sides.

After calculating the capacity of these two planks, we need to replace one plank to continue calculating the capacity. Which plank to replace? We should replace the short plank, because if we replace the long plank, then our The capacity can only be reduced because the height of the container is already determined by the shortest piece of wood. Since we change the planks from the outside, the width of the container can only be shortened but not lengthened.

So we replace the shortest piece of wood each time, and then update the maximum capacity in the process

class Solution {
public:
    int maxArea(vector<int>& height) {
        auto capacity=[&height](int begin,int end)->int{
            int h=height[begin]<height[end]?height[begin]:height[end];
            int width=end-begin;
            return h*width;
        };
        int max=0;
        int left=0,right=height.size()-1;
        while(left!=right){
            int c=capacity(left,right);
            max=max<c?c:max;
            if(height[left]<height[right]){
                left++;
            }else{
                right--;
            }
        }
        return max;
    }
};

おすすめ

転載: blog.csdn.net/weixin_62264287/article/details/134767483