https://leetcode.com/problems/container-with-most-water/
Topic:
Given n non-negative integers A1, A2, ..., an, where each represents a point at Coordi Nate (i, ai). N Vertical Lines is drawn such that the the both endpoints of line I am at (i, ai) and ( i, 0). Find lines, which together with X-axis forms a container, such that the container contains the most water.
Note:you may not slant the container.
Ideas:
Consider reducing the range from the border to the inside. It is important to note that, assuming that the height of the boundary now is a and B, then there are other points in the interior that can be larger than A and B frames, then this point must be larger than the smallest of a and B. So it keeps shrinking from the smaller points of the boundary height until the interior is empty.
Simply iterate through the array once, so the complexity is O (n).
AC Code:
1 classSolution {2 Public:3 intMaxarea (vector<int>&height) {4 intI,j,n=height.size (), a=0, b=n-1, Contain=min (height[0],height[n-1]) * (n1);5 while(a<b) {6 if(height[a]<Height[b]) {7 for(i=a;i<b;i++){8 if(height[i]>Height[a])9 Break;Ten } One if(min (Height[i],height[b]) * (b-i) >contain) { AContain=min (Height[i],height[b]) * (b-i); - } -A=i; the } - Else{ - for(j=b;j>a;j--){ - if(height[j]>Height[b]) + Break; - } + if(min (Height[j],height[a]) * (J-A) >contain) { AContain=min (Height[j],height[a]) * (J-a); at } -b=J; - } - } - returncontain; - } in};
Leetcode (11) The puzzle: Container with the most water