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.
Code
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
Big-O Complexity VisualizerVisualize and compare algorithm time complexities like O(1), O(log n), O(n), O(n log n), and O(n²). Plot growth curves to understand performance scaling at a glance.cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.