Golang盛最多水的容器

题目

Golang 实现给定 n 个非负整数 a1,a2,…,an,每个数代表坐标中的一个点 (i, ai) 。在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (i, ai) 和 (i, 0)。找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。

说明:你不能倾斜容器,且 n 的值至少为 2。

11_golang盛最多水的容器.png

图中垂直线代表输入数组 [1,8,6,2,5,4,8,3,7]。 在此情况下,容器能够容纳水(表示为蓝色部分)的最大值为 49。

示例1

输入: [1,8,6,2,5,4,8,3,7] 输出: 49

代码具体实现

package main import ( "fmt" ) func maxArea(height []int) int { head := 0 tail := len(height) - 1 max := 0 for head != tail { tmp := 0 if height[head] < height[tail] { tmp = (tail - head) * height[head] head++ } else { tmp = (tail - head) * height[tail] tail-- } if tmp > max { max = tmp } } return max } func maxArea2(height []int) int { max := 0 for i := 0; i < len(height); i++ { for j := i + 1; j < len(height); j++ { high := 0 if height[i] >= height[j] { high = height[j] } else { high = height[i] } water := high * (j - i) if water > max { max = water } } } return max } func main() { fmt.Println("嗨客网(www.haicoder.net)") var height = []int{1,8,6,2,5,4,8,3,7} fmt.Println(maxArea(height)) }

程序运行后,控制台输出如下:

12_golang盛最多水的容器.png

我们输入了测试用例,输出了正确结果。