1. 程式人生 > >【leetcode】11.Container With Most Water(c語言)

【leetcode】11.Container With Most Water(c語言)

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; }

執行結果: 在這裡插入圖片描述