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.
題目大意:給定一個長度爲n的數組a[n],在二維空間形成n個點(x=i,y=a[i]),找出兩個點,使得這兩個點到x軸的垂線與x軸構成一個容器,容器的容積最大。容器不能傾斜,而且n>=2。
解題思路:
對於n個點,要求得最大的容積,可以分兩種情況:
1. 寬度爲n,高度爲a[0]和a[n-1]中較小的值;
2. 捨棄掉(i,a[i])這個點,其中i = a[0]和a[n-1]中較小的值的下標,然後在剩下的n-1個點中找得兩個點,構成容積最大的容器。
直到寬度爲1的時候,直接去高度爲a[i]。
遞歸代碼:(leetcode測試用例太大,報了StackOverFlow)
class Solution {
public int findMax(int left, int right, int[] height) {
if (right - left == 1) {
return Math.min(height[left], height[right]);
}
int bigger;
if (height[left] > height[right]) {
bigger = findMax(left, right - 1, height);
} else {
bigger = findMax(left + 1, right, height);
}
return Math.max(Math.min(height[left], height[right]) * (right - left), bigger);
}
public int maxArea(int[] height) {
return findMax(0, height.length - 1, height);
}
}
class Solution {
public int maxArea(int[] height) {
int len = height.length;
int[] area = new int[len];
int left = 0, right = len - 1;
while (right > left) {
area[right - left - 1] = (right - left) * Math.min(height[left], height[right]);
if (height[left] > height[right]) {
right--;
} else {
left++;
}
}
int max = 0;
for (int i = 0; i < len; i++) {
if (area[i] > max) {
max = area[i];
}
}
return max;
}
}