題目:
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.
題解:
這道題挺類似二分查詢法的,這道題是先從兩頭開始算面積,面積的計算要由短板決定,並維護一個當前最大面積。
然後逐步替換小的短板來計算面積。每一步只替換短板的原因是,短板決定面積,而高板不影響,所以要想有所改變就改變那個有決定性的東西。。
網上有好多人都畫出圖來了。。可以搜搜看。。。
程式碼如下:
1 public int maxArea(int[] height) {
2 if(height == null || height.length == 0)
3 return 0;
4
5 int low = 0, high = height.length -1 ;
6 int max = 0;
7 while (low < high) {
8 int area = (high-low)*Math.min(height[low], height[high]);
9
10 max = Math.max(max, area);
11 if (height[low] < height[high])
12 low++;
13 else
14 high--;
15 }
16 return max;
17 }
2 if(height == null || height.length == 0)
3 return 0;
4
5 int low = 0, high = height.length -1 ;
6 int max = 0;
7 while (low < high) {
8 int area = (high-low)*Math.min(height[low], height[high]);
9
10 max = Math.max(max, area);
11 if (height[low] < height[high])
12 low++;
13 else
14 high--;
15 }
16 return max;
17 }