Container With Most Water

July 6, 2025

Question

Given an array where each element represents the height of a vertical line on the x-axis, you need to find two lines that together with the x-axis form a container that holds the most water.

You may not slant the container – only vertical sides are allowed.

Example

Input: [1, 8, 9, 2, 1, 8, 2, 0, 7]

Output: 49

Explanation: Max area is formed between height 8 (index 1) and height 7 (index 8): min(8, 7) × (8 - 1) = 7 × 7 = 49.


Input: [1, 1]

Output: 1

Explanation: 1 × 1 = 1

Visual

0 1 2 3 4 5 6 7 8 9 10 0 1 2 3 4 5 6 7 8 Max Area = 49 between index 1 and 8

My Notes

package main

import (
	"fmt"
)

func main() {
	result := maxArea([]int{8,7,2,1})
	fmt.Println(result)
}

func maxArea(height []int) int {
	i, j, minHeight, currentArea, maxArea := 0, len(height) - 1, 0, 0, 0

	for i < j {
		if height[i] < height[j] {
			minHeight = height[i]
		} else {
			minHeight = height[j]
		}
		currentArea = (j - i) * minHeight

		if maxArea < currentArea {
			maxArea = currentArea
		}
		if height[i] < height[j] {
			i++
		} else {
			j--
		}
	}

	return maxArea
}