Double pointer: the container holding the most water (4.18leetcode one question per day)

You are given n non-negative integers a1, a2, ..., an, and each number represents a point (i, ai) in coordinates. Draw n vertical lines in the coordinates. The two endpoints of vertical line i are (i, ai) and (i, 0). Find two of the lines so that the container they form with the x-axis can hold the most water.
Note: You cannot tilt the container, and the value of n is at least 2.

Examples:

Input: [1,8,6,2,5,4,8,3,7]
 Output: 49 
Idea: Double pointer, see the code is clear and easy to understand
 1 int maxArea(vector<int>& height) 
 2     {
 3         int res = 0;
 4         int i = 0;
 5         int j = height.size()-1;
 6 
 7         while(i < j)
 8         {
 9             int area = (j-i) * min(height[i],height[j]);
10             res = max(area,res);
11             if(height[i] < height[j])
12             {
13                 i++;
14             }
15             else
16             {
17                 j--;
18             }
19         }
20         return res;
21     }

 




 

Guess you like

Origin www.cnblogs.com/ZhengLijie/p/12724121.html