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.
Note: You may not slant the container and n is at least 2.
1 public class Solution { 2 public int maxArea(int[] height) { 3 if (height == null || height.length < 2) { 4 return 0; 5 } 6 7 int l = 0; 8 int r = height.length - 1; 9 int max = 0; 10 while (l < r) 11 { 12 int area = 0; 13 if (height[l] > height[r]) { 14 area = height[r] * (r - l); 15 r--; 16 } else { 17 area = height[l] * (r - l); 18 l++; 19 } 20 if (area > max) { 21 max = area; 22 } 23 } 24 25 return max; 26 } 27 }

浙公网安备 33010602011771号