Skip to content

Commit

Permalink
Merge pull request #75 from arunsathiya/solve/42-trapping-rain-water
Browse files Browse the repository at this point in the history
42. Trapping Rain Water
  • Loading branch information
arunsathiya committed Feb 26, 2024
2 parents e0ce631 + 77b10b3 commit fc42b65
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 0 deletions.
25 changes: 25 additions & 0 deletions src/42-trapping-rain-water/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package main

func trap(height []int) int {
leftMax, rightMax := 0, 0
left, right := 0, len(height)-1
totalTrap := 0
for left < right {
if height[left] <= height[right] {
if height[left] >= leftMax {
leftMax = height[left]
} else {
totalTrap += leftMax - height[left]
}
left++
} else {
if height[right] >= rightMax {
rightMax = height[right]
} else {
totalTrap += rightMax - height[right]
}
right--
}
}
return totalTrap
}
30 changes: 30 additions & 0 deletions src/42-trapping-rain-water/main_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package main

import (
"testing"
)

func TestTrap(t *testing.T) {
tests := []struct {
height []int
want int
}{
{
height: []int{0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1},
want: 6,
},
{
height: []int{4, 2, 0, 3, 2, 5},
want: 9,
},
}

for _, tt := range tests {
t.Run("", func(t *testing.T) {
got := trap(tt.height)
if got != tt.want {
t.Errorf("trap(%v) = %v, want %v", tt.height, got, tt.want)
}
})
}
}

0 comments on commit fc42b65

Please sign in to comment.