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
My Notes
- Use two pointers: one at the start, one at the end.
- At each step, calculate the area formed by the shorter line.
- Move the pointer pointing to the shorter line inward.
- Keep track of the maximum area seen so far.
-
Time complexity:
O(n)
, Space complexity:O(1)
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 }