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 and 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.
For this problem, the first is to use the method of violence, the complexity of O (N2),
1 PackageContainer.With.Most.Water;2 3 Public classContainerwithmostwater {4 5 /**6 * @paramargs7 */8 Public Static voidMain (string[] args) {9 //TODO auto-generated Method StubTen intheight[]={1,2,3,4}; One intMaxarea=maxarea (height); A System.out.println (Maxarea); - } - the Public Static intMaxarea (int[] height) { - intMaxarea=0; - for(inti=0;i){ - for(intj=i+1;j){ + intminheight=math.min (Height[i], height[j]); - intkuan=j-i; + inttemparea=kuan*MinHeight; A if(temparea>Maxarea) atMaxarea=Temparea; - } - } - returnMaxarea; - } - in}
This situation directly timed out, then according to the nature of the problem can take a linear complexity method
1. First, suppose we find the longitudinal line that can take the maximum volume as I, J (assuming I<j), then the maximum volume C = min (ai, AJ) * (j-i);
2. Let's look at a property like this:
①: No line at the right end of J will be higher than it! Hypothesis exists K | (j<k && ak > AJ), then by ak> aj, so min (Ai,aj, AK) =min (AI,AJ), so the volume of the container consisting of I, k c ' = min (ai,aj) * (k-i) > C, and C is the most value contradiction, so the proof of J will not have a higher line than it;
②: Similarly, there will be no higher line on the left side of I;
What does that mean? If we currently get the candidate: set to X, y two lines (x< y), then be able to get a larger volume than its new two edges necessarily within the [x, Y] interval and ax ' > =ax, ay ' >= ay;
3. So we move from the two to the middle, while updating the candidate values, in the contraction interval priority from the X, y of the smaller edge of the contraction;
Start at both ends and gradually shrink
1 PackageContainer.With.Most.Water;2 3 Public classContainerWithMostWater1 {4 5 /**6 * @paramargs7 */8 Public Static voidMain (string[] args) {9 //TODO auto-generated Method StubTen intheight[]={1,2,3,4}; One intMaxarea=maxarea (height); A System.out.println (Maxarea); - } - Public Static intMaxarea (int[] height) { the intMaxarea=0; - intI=0; - intJ=height.length-1; - while(i!=j) { + intTemparea= (j-i) *math.min (Height[i], height[j]); - if(temparea>Maxarea) + { AMaxarea=Temparea; at } - if(height[i]<Height[j]) { -i++; -}Else{ -j--; - } in } - returnMaxarea; to } +}
Leetcode Container with most water