[LeetCode] Container With Most Water

int maxArea(vector<int> &height) {
	int n = height.size();
	if(n < 2)
	{
		return 0;
	}
	int left = 0, right = n-1;
	int minheight = height[left] < height[right] ? height[left] : height[right];
	int maxArea = (right - left)*minheight;
	while(left < right)
	{
		for(; left < right; left++)
		{
			if(height[left] > minheight)
			{
				break;
			}
		}
		for(; right > left; right--)
		{
			if(height[right] > minheight)
			{
				break;
			}
		}
		minheight = height[left] < height[right] ? height[left] : height[right];
		int newArea = (right - left)*minheight;
		if(newArea > maxArea)
		{
			maxArea = newArea;
		}
	}
	return maxArea;
}

基本思想:以首尾的高度初始化为容器的左右壁,

从左壁位置向右找出比容器更高的高度作为新容器的左壁,

从右壁位置向左找出比容器更高的高度作为新容器的右壁,

若新容器的容积比原容器大,则更新最大容积,

继续按上述方法寻找新容器、更新容积,直至找不到新容器为止。

你可能感兴趣的:([LeetCode] Container With Most Water)