Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 60 additions & 0 deletions 2_two_pointers/4_container_with_most_water/solution.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
package containerwithmostwater

// Time complexity: O(n^2)
// Space complexity: O(1)
func MaxAreaBruteForce(heights []int) int {
n := len(heights)
maxArea := 0

for p1 := 0; p1 < n; p1++ {
for p2 := p1 + 1; p2 < n; p2++ {
height := heights[p1]
if heights[p2] < height {
height = heights[p2]
}
width := p2 - p1
area := height * width

if area > maxArea {
maxArea = area
}

// height := min(heights[p1], heights[p2])
// width := p2 - p1
// area := height * width
// maxArea = max(maxArea, area)
}
}
return maxArea
}

// Time complexity: O(n)
// Space complexity: O(1)
func MaxAreaTwoPointers(heights []int) int {
p1, p2, maxArea := 0, len(heights)-1, 0

for p1 < p2 {
height := heights[p1]
if heights[p2] < height {
height = heights[p2]
}
width := p2 - p1
area := height * width

if area > maxArea {
maxArea = area
}

// height := min(heights[p1], heights[p2])
// width := p2 - p1
// area := height * width
// maxArea = max(maxArea, area)

if heights[p1] < heights[p2] {
p1++
} else {
p2--
}
}
return maxArea
}
37 changes: 37 additions & 0 deletions 2_two_pointers/4_container_with_most_water/solution_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package containerwithmostwater

import "testing"

func TestMaxArea(t *testing.T) {
cases := []struct {
name string
fn func([]int) int
heights []int
expected int
}{
// MaxAreaBruteForce
{"BruteForce - Example 1", MaxAreaBruteForce, []int{1, 7, 2, 5, 4, 7, 3, 6}, 36},
{"BruteForce - Example 2", MaxAreaBruteForce, []int{2, 2, 2}, 4},
{"BruteForce - Minimal input size 2", MaxAreaBruteForce, []int{1, 1}, 1},
{"BruteForce - All zeroes", MaxAreaBruteForce, []int{0, 0, 0, 0}, 0},
{"BruteForce - Increasing heights", MaxAreaBruteForce, []int{1, 2, 3, 4, 5}, 6},
{"BruteForce - Decreasing heights", MaxAreaBruteForce, []int{5, 4, 3, 2, 1}, 6},

// MaxAreaTwoPointers
{"TwoPointers - Example 1", MaxAreaTwoPointers, []int{1, 7, 2, 5, 4, 7, 3, 6}, 36},
{"TwoPointers - Example 2", MaxAreaTwoPointers, []int{2, 2, 2}, 4},
{"TwoPointers - Minimal input size 2", MaxAreaTwoPointers, []int{1, 1}, 1},
{"TwoPointers - All zeroes", MaxAreaTwoPointers, []int{0, 0, 0, 0}, 0},
{"TwoPointers - Increasing heights", MaxAreaTwoPointers, []int{1, 2, 3, 4, 5}, 6},
{"TwoPointers - Decreasing heights", MaxAreaTwoPointers, []int{5, 4, 3, 2, 1}, 6},
}

for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
got := c.fn(c.heights)
if got != c.expected {
t.Errorf("%s failed: expected %v, got %v", c.name, c.expected, got)
}
})
}
}
Loading