Container With Most Water
Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.
两个指针问题。需要计算的是两条线之间的最大面积。使用两个指针,先结算小的那边,因为这边此时的高度成为了下界,不移动这边的话,其他任何情况都会有此下界而且长度变短。
1 public int maxArea(int[] height) { 2 if (height == null || height.length < 2) { 3 return 0; 4 } 5 int left = 0; 6 int right = height.length - 1; 7 int res = 0; 8 while (left < right) { 9 if (height[left] < height[right]) { 10 res = Math.max(res, height[left] * (right - left)); 11 left++; 12 } else { 13 res = Math.max(res, height[right] * (right - left)); 14 right--; 15 } 16 } 17 return res; 18 }