DevPath

← All problems

Container With Most Water

Medium arrays · two-pointers

Description

Each number is the height of a vertical line. Return the maximum area of water a pair of lines can hold.

Constraints

2 <= n <= 100000; 0 <= height

Examples

Input: height = [1,8,6,2,5,4,8,3,7]

Output: 49

Hints (1)
  • Start with the widest pair and always move the shorter line inward.

Solutions

Two pointers, move the shorter side in. · Time O(n) · Space O(1)

func maxArea(height []int) int {
    i, j, best := 0, len(height)-1, 0
    for i < j {
        h := height[i]
        if height[j] < h {
            h = height[j]
        }
        if area := h * (j - i); area > best {
            best = area
        }
        if height[i] < height[j] {
            i++
        } else {
            j--
        }
    }
    return best
}

Create a free account to submit solutions, track progress and save problems.

Create account