Container With Most Water Two Pointers

Squeeze two pointers inward always moving the shorter wall, since it caps the area, so the maximum container is found in one pass.

GoData Integrity

Code

gosnippet
32 lines
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}))
}

The flow of the file

The snippet is organized around the functions maxArea and main.

The loop for left < right is the only repeated construct.

Watch out for

  • Zero packages pulled in — the runtime ships every API this code touches.

Putting it to use

Entry signature: func maxArea(height []int) int

The demo flow inside main is maxArea — run the file to see it end to end.

Core lines

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

Interactive Tools for This Topic

FAQ

How do you run Container With Most Water Two Pointers?
Run it as a complete program — compile or interpret the file directly; there is nothing to install first.