We want to find out how much water can be held between two sticks. The heights of our sticks are:
height = [1, 2, 4, 3]
Indexes ( 0, 1, 2, 3
)
We use two pointers: one at the left end and one at the right end.
Formula for water:area = min(height[left], height[right]) × (right - left)
Step 1:
left = 0 , right = 3
height[left] = 1
height[right] = 3
min(height[left], height[right]) = min(1,3) = 1
width = right - left = 3 - 0 = 3
area = 1 × 3 = 3
Max area so far = 3
Sinceheight[left] < height[right]
, move left →left = 1
.
Step 2:
left = 1 , right = 3
height[left] = 2
height[right] = 3
min(height[left], height[right]) = min(2,3) = 2
width = 3 - 1 = 2
area = 2 × 2 = 4
Max area so far = 4
Sinceheight[left] < height[right]
, move left →left = 2
.
Step 3:
left = 2 , right = 3
height[left] = 4
height[right] = 3
min(height[left], height[right]) = min(4,3) = 3
width = 3 - 2 = 1
area = 3 × 1 = 3
Max area still = 4
Sinceheight[left] > height[right]
, move right →right = 2
.
Step 4:
left = 2 , right = 2
Both pointers meet, so stop.
Final Answer:
The maximum water area = 4, between left = 1
and right = 3
height[left] = 2
height[right] = 3
Golang implementation of the problem
package main
import (
"fmt"
)
func maxArea(height []int) int {
left := 0
right := len(height) - 1
maxArea := 0
for left < right {
// take the smaller height between left and right
h := height[left]
if height[right] < h {
h = height[right]
}
// width = distance between left and right
width := right - left
area := h * width
// update maximum area if needed
if area > maxArea {
maxArea = area
}
// move the pointer with smaller height
if height[left] < height[right] {
left++
} else {
right--
}
}
return maxArea
}
func main() {
height := []int{1, 2, 4, 3}
fmt.Println("Maximum Area:", maxArea(height)) // Output: 4
}