Leetcode holds the most water container c++

Given n non-negative integers a1, a2,..., an, each number represents a point (i, ai) in the coordinates. Draw n vertical lines in the coordinates. The two end points of the vertical line i are (i, ai) and (i, 0). Find two of the lines so that the container that they form with the x-axis can hold the most water.

Explanation: You cannot tilt the container, and the value of n is at least 2.

Example:

输入: [1,8,6,2,5,4,8,3,7]
输出: 49

Solution 1: Violence

class Solution {
public:
    int maxArea(vector<int>& height) {
        int res=0;
        for(int i=0;i<height.size();i++)
        {
            for(int j=i+1;j<height.size();j++)
            {
                int temp1=min(height[i],height[j]);
                int temp2=temp1*(j-i);
                res=max(res,temp2);
            }
        }
        return res;
    }
};

Solution 2: Double pointer method

Move the pointer with small capacity into the array

class Solution {
public:
    int maxArea(vector<int>& height) {
        int i=0;
        int j=height.size()-1;
        int res=0;
        while(i<j)
        {
            int temp1=min(height[i],height[j]);//容量由最小的决定
            int temp2=temp1*(j-i);
            res=max(res,temp2);
            if(height[i]<height[j])
                i++;
            else j--;
        }
        return res;
    }
};

Guess you like

Origin blog.csdn.net/weixin_39139505/article/details/90231651