← 中文资源

简体中文版本

双指针求盛最多水的容器

左右指针夹逼,每次移动较矮的一侧再结算面积:容积由短板决定,移动较高的一侧只会让宽度变小而面积不可能变大,因此一次线性扫描就能得到最大容积。

阅读英文原文

实现说明

双指针求盛最多水的容器可以归结为函数 maxArea、main。 驱动整个流程的是 for left < right 这一个循环。

使用要点

  • main 按顺序串起 maxArea;运行文件就会把这个流程跑一遍。

常见问题

「双指针求盛最多水的容器」这个示例怎么运行?

直接执行即可——程序只依赖运行时自身。

主签名形如 func maxArea(height []int) int

核心语句

func main() {
	fmt.Println(maxArea([]int{1, 8, 6, 2, 5, 4, 8, 3, 7}))
	fmt.Println(maxArea([]int{1, 1}))
	fmt.Println(maxArea([]int{4, 3, 2, 1, 4}))
}

代码示例

package main

import "fmt"

// maxArea: container with most water — move the shorter wall inward,
// because it is the one capping the area
func maxArea(height []int) int {
	left, right := 0, len(height)-1
	best := 0
	for left < right {
		width := right - left
		h := height[left]
		if height[right] < h {
			h = height[right]
		}
		if area := width * h; area > best {
			best = area
		}
		if height[left] < height[right] {
			left++
		} else {
			right--
		}
	}
	return best
}

func main() {
	fmt.Println(maxArea([]int{1, 8, 6, 2, 5, 4, 8, 3, 7}))
	fmt.Println(maxArea([]int{1, 1}))
	fmt.Println(maxArea([]int{4, 3, 2, 1, 4}))
}