Topic
GivenNnon-negative integersa1 ,a2 , ...,an , where each represents a point at coordinate (I,ai ).NVertical lines is drawn such that the both endpoints of lineIis 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.
Resolution
Test instructions: In a two-dimensional coordinate system, (I, AI) represents a segment from (I, 0) to (i, AI), and any two of such segments and X-axes make up a cask to find the cask that can hold the most water and return its volume.
Two-tier for-loop violence will time out, so abandon this lazy idea as soon as possible.
Is there an O (n) solution?
The answer is, with two pointers from both ends to the middle, if the left side of the short less right operand end, then right shift, and the right side of the left shift, know that both ends move to the middle of the overlap, recording the process of each composition of the volume of barrels, return the largest. (Think about why this is reasonable?) )
public class Solution {public int maxarea (int[] height) { if (Height.length < 2) return 0; int ans = 0; int l = 0; int r = height.length-1; while (L < r) { int v = (r-l) * Math.min (Height[l], height[r]); if (V > ans) ans = v; if (Height[l] < height[r]) l++; else r--; } return ans; }}
Rationality explanation: When the left segment L is less than the right end segment R, we move the l to the right, then discard the L and the right end of the other segments (R-1, R-2, ...) Wooden barrels, these barrels are not necessary to judge, because the volume of these barrels is certainly not a large volume of barrels of L and R.
"Leetcode" Container with the most water problem solving report