Browse Source

add 'Container With Most Water'

tangs 5 years ago
parent
commit
f551b9bf72
1 changed files with 38 additions and 0 deletions
  1. 38 0
      tags/array/ContainerWithMostWater/main.go

+ 38 - 0
tags/array/ContainerWithMostWater/main.go

@@ -0,0 +1,38 @@
+package main
+
+import (
+	"fmt"
+)
+
+func main() {
+	var height []int
+
+	height = []int{1, 8, 6, 2, 5, 4, 8, 3, 7}
+	fmt.Println(maxArea(height))
+
+	height = []int{3, 6, 2, 5, 9, 4, 3}
+	fmt.Println(maxArea(height))
+}
+
+func maxArea(height []int) int {
+	if len(height) == 0 {
+		return 0
+	}
+
+	var front, back = 0, len(height) - 1
+	var max = 0
+	var tempHeight int
+	for front != back {
+		if height[front] < height[back] {
+			tempHeight = height[front] * (back - front)
+			front++
+		} else {
+			tempHeight = height[back] * (back - front)
+			back--
+		}
+		if tempHeight > max {
+			max = tempHeight
+		}
+	}
+	return max
+}