跳到主要内容

11. 盛最多水的容器

mid

给出一个非负整数数组 a1,a2,a3,…… an,每个整数标识一个竖立在坐标轴 x 位置的一堵高度为 ai 的墙,选择两堵墙,和 x 轴构成的容器可以容纳最多的水。

image-20220227155740486

对撞指针

func maxArea(height []int) int {
start, end := 0, len(height)
curResult, maxResult := 0, 0
for start < end {
curWidth := end - start
curHeight := 0
// 因为高度取矮者 矮的一边的指针就可以往中间移动 因为反过来的移法面积必定更小
if height[start] < height[end] {
curHeight = height[start]
start++
} else {
curHeight = height[end]
end--
}

curResult = curWidth * curHeight
if curResult > maxResult {
maxResult = curResult
}
}
return maxResult
}