Skip to content

Commit

Permalink
Create: 42-Trapping-Rain-Water.go
Browse files Browse the repository at this point in the history
  • Loading branch information
Ykhan799 authored Sep 12, 2022
1 parent 810d31e commit 28929d6
Showing 1 changed file with 30 additions and 0 deletions.
30 changes: 30 additions & 0 deletions go/42-Trapping-Rain-Water.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
func trap(height []int) int {
if height == nil {
return 0
}

left, right := 0, len(height) - 1
leftMax, rightMax := height[left], height[right]
res := 0

for left < right {
if leftMax < rightMax {
left += 1
leftMax = max(leftMax, height[left])
res += leftMax - height[left]
} else {
right -= 1
rightMax = max(rightMax, height[right])
res += rightMax - height[right]
}
}
return res
}

// Golang does not have a built-in max for integers
func max(a int, b int) int {
if a > b {
return a;
}
return b;
}

0 comments on commit 28929d6

Please sign in to comment.