11. Container With Most Water (Array)
阿新 • • 發佈:2018-07-31
current return 計算 int 去掉 ++ with pan solution
O(n)的方法,兩邊開始計算最wide的container, 因為往中間走的話,要想遇到更max的,需要更高的smaller height,因此可以去掉已經計算過的smaller的height。
1 //Old 2 class Solution { 3 public int maxArea(int[] height) { 4 int max = 0; 5 int size = height.length; 6 for(int i = 0; i < size - 1; i++) { 7 for(intj = i + 1; j < size; j++) { 8 int lower = height[i] < height[j] ? height[i]:height[j]; 9 if(max < lower * (j - i)) { 10 max = lower * (j - i); 11 } 12 } 13 } 14 return max; 15 } 16 } 17 18//New 19 20 class Solution { 21 public int maxArea(int[] height) { 22 int max = 0; 23 int size = height.length; 24 int l = 0, r = size - 1; 25 while(l < r) { 26 int current = Math.min(height[l], height[r]) * (r - l); 27 if(current > max) max= current;28 if(height[l] < height[r]) { 29 l++; 30 }else { 31 r--; 32 } 33 } 34 return max; 35 } 36 }
11. Container With Most Water (Array)