package main import "fmt" func trap(height []int) int { n := len(height) if n == 0 { return 0 } leftMax := make([]int, n) rightMax := make([]int, n) leftMax[0] = height[0] for i := 1; i < n; i++ { if height[i] > leftMax[i-1] { leftMax[i] = height[i] } else { leftMax[i] = leftMax[i-1] } } rightMax[n-1] = height[n-1] for i := n - 2; i >= 0; i-- { if height[i] > rightMax[i+1] { rightMax[i] = height[i] } else { rightMax[i] = rightMax[i+1] } } water := 0 for i := 0; i < n; i++ { minHeight := leftMax[i] if rightMax[i] < minHeight { minHeight = rightMax[i] } if minHeight > height[i] { water += minHeight - height[i] } } return water } func main() { height := []int{0,1,0,2,1,0,1,3,2,1,2,1} fmt.Println(trap(height)) }
The code calculates the trapped water by finding the maximum height to the left and right of each bar, then sums the water trapped at each position.
For the input array, the total trapped water is 6 units.
leftMax[i] stores the tallest bar from the left up to index i.
rightMax[i] stores the tallest bar from the right up to index i.
These help determine the water level at each position.
package main import "fmt" func trap(height []int) int { n := len(height) leftMax := make([]int, n) rightMax := make([]int, n) leftMax[0] = height[0] for i := 1; i <= n; i++ { if height[i] > leftMax[i-1] { leftMax[i] = height[i] } else { leftMax[i] = leftMax[i-1] } } return 0 } func main() { fmt.Println(trap([]int{0,1,0,2})) }
The loop uses i <= n, but valid indices go from 0 to n-1.
Accessing height[i] when i == n causes an index out of range runtime error.
package main import "fmt" func trap(height []int) int { left, right := 0, len(height)-1 leftMax, rightMax := 0, 0 water := 0 for left < right { if height[left] < height[right] { if height[left] >= leftMax { leftMax = height[left] } else { water += leftMax - height[left] } left++ } else { if height[right] >= rightMax { rightMax = height[right] } else { water += rightMax - height[right] } right-- } } return water } func main() { fmt.Println(trap([]int{4,2,0,3,2,5})) }
The two-pointer approach calculates trapped water by moving pointers inward and updating max heights.
For the input, total trapped water is 9 units.
The two-pointer method moves left and right pointers inward, each visiting elements once.
Thus, the time complexity is linear, O(n).
