Description:
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.
Example1:
Input: [1,8,6,2,5,4,8,3,7]
Output: 49
解法一:穷举
提交代码:
int maxArea(int* height, int heightSize)
{
int i,j,shortline;
int maxArea=0;
for (i = 0; i <heightSize;i++)
for (j = i + 1; j < heightSize; j++)
{
if (height[i] < height[j]) shortline = height[i];
else shortline = height[j];
if ((j - i)*shortline > maxArea)
maxArea = (j - i)*shortline;
}
return maxArea;
}
运行结果:
解法二:贪心算法
提交代码:
int maxArea(int* height, int heightSize)
{
int left = 0, right = heightSize - 1;
int shortline, currentArea, maxArea = 0;
while (left != right)
{
if (height[left] > height[right])
{
shortline = height[right];
currentArea = (right - left)*shortline;
if (currentArea > maxArea)
maxArea = currentArea;
right--;
}
else
{
shortline = height[left];
currentArea = (right - left)*shortline;
if (currentArea > maxArea)
maxArea = currentArea;
left++;
}
}
return maxArea;
}
运行结果: