跳到主要内容

11-盛最多水的容器

题目

11. 盛最多水的容器 - 力扣(LeetCode)

难度中等

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

**说明:**你不能倾斜容器。

/*
* @lc app=leetcode.cn id=11 lang=golang
*
* [11] 盛最多水的容器
*/

// @lc code=start
func maxArea(height []int) int {
// 双指针
left, right := 0, len(height)-1
max := 0

for left < right {
// 计算面积
area := (right - left) * min(height[left], height[right])
max = maxInt(max, area)

// 移动指针
if height[left] < height[right] {
left++
} else {
right--
}
}

return max
}

func maxInt(x, y int) int {
if x > y {
return x
}
return y
}