From 84c4a7f6437a2689ff8fbbc48a1059f05f12d32e Mon Sep 17 00:00:00 2001 From: openset Date: Tue, 11 Jun 2019 12:24:20 +0800 Subject: [PATCH] Add: Container With Most Water --- .../container_with_most_water.go | 16 ++++++++++++ .../container_with_most_water_test.go | 26 +++++++++++++++++++ 2 files changed, 42 insertions(+) diff --git a/problems/container-with-most-water/container_with_most_water.go b/problems/container-with-most-water/container_with_most_water.go index b299c752c..6f96abfe8 100644 --- a/problems/container-with-most-water/container_with_most_water.go +++ b/problems/container-with-most-water/container_with_most_water.go @@ -1 +1,17 @@ package container_with_most_water + +func maxArea(height []int) int { + ans, l, r := 0, 0, len(height)-1 + for l < r { + w, h := r-l, height[l] + if h < height[r] { + l++ + } else { + h, r = height[r], r-1 + } + if area := w * h; area > ans { + ans = area + } + } + return ans +} diff --git a/problems/container-with-most-water/container_with_most_water_test.go b/problems/container-with-most-water/container_with_most_water_test.go index b299c752c..9bf75977d 100644 --- a/problems/container-with-most-water/container_with_most_water_test.go +++ b/problems/container-with-most-water/container_with_most_water_test.go @@ -1 +1,27 @@ package container_with_most_water + +import "testing" + +type caseType struct { + input []int + expected int +} + +func TestMaxArea(t *testing.T) { + tests := [...]caseType{ + { + input: []int{1, 8, 6, 2, 5, 4, 8, 3, 7}, + expected: 49, + }, + { + input: []int{1, 8, 6, 30, 20, 6, 9, 10, 1}, + expected: 48, + }, + } + for _, tc := range tests { + output := maxArea(tc.input) + if output != tc.expected { + t.Fatalf("input: %v, output: %v, expected: %v", tc.input, output, tc.expected) + } + } +}