From 5fb803129fc71f0f61a439b45e3c2f0690411f66 Mon Sep 17 00:00:00 2001 From: "M.V. Hutz" Date: Mon, 12 Jan 2026 19:38:01 -0500 Subject: [PATCH] feat: monday --- pkg/trapping_rain_water/main.go | 31 ++++++++++++++++++++++++++++ pkg/trapping_rain_water/main_test.go | 31 ++++++++++++++++++++++++++++ 2 files changed, 62 insertions(+) create mode 100644 pkg/trapping_rain_water/main.go create mode 100644 pkg/trapping_rain_water/main_test.go diff --git a/pkg/trapping_rain_water/main.go b/pkg/trapping_rain_water/main.go new file mode 100644 index 0000000..ba6a18c --- /dev/null +++ b/pkg/trapping_rain_water/main.go @@ -0,0 +1,31 @@ +package trapping_rain_water + +func Trap(heights []int) int { + // Calculate area taken up by the boundary. + boundary_area := 0 + for _, height := range heights { + boundary_area += height + } + + // Calculate the total area taken up by the boundary and the water. + total_area := 0 + left := 0 + left_height := 0 + right := len(heights) - 1 + right_height := 0 + + for left <= right { + left_height = max(left_height, heights[left]) + right_height = max(right_height, heights[right]) + + if left_height < right_height { + total_area += left_height + left++ + } else { + total_area += right_height + right-- + } + } + + return total_area - boundary_area +} diff --git a/pkg/trapping_rain_water/main_test.go b/pkg/trapping_rain_water/main_test.go new file mode 100644 index 0000000..3e1d7f2 --- /dev/null +++ b/pkg/trapping_rain_water/main_test.go @@ -0,0 +1,31 @@ +package trapping_rain_water + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestTrap_Example1(t *testing.T) { + height := []int{0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1} + expected := 6 + result := Trap(height) + + assert.Equal(t, expected, result) +} + +func TestTrap_Example2(t *testing.T) { + height := []int{4, 2, 0, 3, 2, 5} + expected := 9 + result := Trap(height) + + assert.Equal(t, expected, result) +} + +func TestTrap_Example3(t *testing.T) { + height := []int{0} + expected := 0 + result := Trap(height) + + assert.Equal(t, expected, result) +}