问题描述:
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.
分析:问题描述的很清楚,但是却想不明白,还是看了网友的做法才恍然大悟。
area=(right-left)*min(height[right],height[left]);
因此,面积是由两个因素决定的。直接找面积最大的是不可能的,只是是控制变量法,先让边最长,即(right-left)是最大的,即选数组的两端的两条边。此时,height[left] 与height[right]大小会不一样。
假设,height[left] ‘<’ height[right],那么只有当left右移才可能会获取最大面积。因为left边是瓶颈。而当right左移的话,只会使面积减少。
- 假设height[left]‘<’height[right-1]‘<’height[right],则min(height[right-1],height[left])= height[left].但边却减少,所以面积减少
- 假设height[right-1]‘<’height[left],则min(height[right-1],height[left])/>height[left].但边却减少,所以面积减少
所以,只有当left右移时才可能会获得更大值。
同理,当height[right]‘<’height[left]时,此时,right左移才会获得更大值。
代码如下:12ms
int maxArea(int* height, int heightSize) {
int left = 0,right = heightSize-1;
int max = 0;
int tmp;
int he;
while(left<right){
he = height[left]-height[right];
if(he<0){
tmp = (right-left)*height[left];
left++;
}else{
tmp = (right-left)*height[right];
right--;
}
if(tmp>max)
max = tmp;
}
return max;
}