一、题目描述
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.
给定n个非负的整数a1,a2 ……an, 其中每个代表一个点坐标(i, ai)。一共n个垂直线段, 从每个坐标到x轴的垂线。找到两个线段,与X轴形成一个容器,使其能盛最多的水。注:不能倾斜容器并且n>=2.
二、思路
盛水量由其最短木板高度决定,设两个指针,一个指向头,一个指向尾,然后向中间移动,并计算出最大盛水量
三、C代码
int maxArea(int* height, int heightSize){
int *i = height, *j = i + heightSize - 1;
int water = 0, w, h;
while(i < j) {
h = *i < *j ? *i : *j;
w = h * (j - i);
if(w > water) water = w;
while(*i <= h && i < j) i++;
while(*j <= h && i < j) j--;
}
return water;
}