Given n non-negative integers,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:采用两层循环进行遍历,外层i范围0--heightSize-1,里层j范围i+1--heightSize,通过求min(height[i] , height[j]) * (j-i) 和max进行比较,对max进行更新
不足之处:当数据量过大时,乘积的结果超过了int的范围,在leetcode中通过情况为46/49
->想法2:改进方法1的不足。这个题目可以考虑到木桶效应,找到两端的最短点乘以间隔即可。如果起点小于终点,那么短板就是起点,最终点对应的就是最大值,之后起点++; 如果起点大于终点,那么终点就是短板,重点--,只要大于起点,一定能找到该起点对应的最大值。
int maxArea(int* height, int heightSize) {
int max=0;
int tmp=0;
int i=0;
int j=heightSize-1;
while(i<j)
{
if(height[i] < height[j])
{
tmp=height[i] * (j-i);
if(tmp > max)
max = tmp;
i++;
}
else
{
tmp=height[j] * (j-i);
if(tmp > max)
max = tmp;
j--;
}
}
return max;
}