Skip to content

Commit

Permalink
11. Container With Most Water
Browse files Browse the repository at this point in the history
  • Loading branch information
blueBlue0102 committed Nov 24, 2024
1 parent e383910 commit cd05092
Show file tree
Hide file tree
Showing 4 changed files with 74 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package leetcode

func ContainerWithMostWater(height []int) int {
left, right := 0, len(height)-1
maxCapacity := 0
for right > left {
capacity := min(height[left], height[right]) * (right - left)
if capacity > maxCapacity {
maxCapacity = capacity
}
if height[left] <= height[right] {
left++
} else {
right--
}
}
return maxCapacity
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package leetcode

import (
"reflect"
"testing"
)

// 填入 function input type
type parameters0011 struct {
height []int
}

func TestContainerWithMostWater(t *testing.T) {
tests := []struct {
parameters0011
// 填入 function output type
ans int
}{
// 填入 test case
{
parameters0011{[]int{1, 8, 6, 2, 5, 4, 8, 3, 7}},
49,
},
{
parameters0011{[]int{1, 1}},
1,
},
}

for _, test := range tests {
t.Run("Test ContainerWithMostWater", func(t *testing.T) {
// 完整輸入參數
result := ContainerWithMostWater(test.parameters0011.height)
// compare 的方式需視情況調整
if !reflect.DeepEqual(result, test.ans) {
t.Errorf("ContainerWithMostWater(%+v) got %+v, want %+v", test.parameters0011, result, test.ans)
}
})
}
}
16 changes: 16 additions & 0 deletions leetcode/0011.Container-With-Most-Water/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# 11. Container With Most Water

<https://leetcode.com/problems/container-with-most-water/>

![example 1](image1.png)

給定數字陣列 `height`,找出能容納最多水容量的空間為多少
要找出使用的是哪兩個 `heigth`,容器的容積等於 $min(h1, h2) \times (x2-x1)$

由於容器一定由左邊和右邊構成,所以可以使用雙指針,並且一個從左一個從右開始
計算出當下的容積後,移動高度較低的指針,往中間靠近
如此便能使用 $O(n)$ 找出最大的容積

## Takeaway

- Two Points
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.

0 comments on commit cd05092

Please sign in to comment.