题目
Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.
Note: You may not slant the container and n is at least 2.
我的代码
方法一:
package main
import (
"fmt"
)
func main() {
fmt.Println(maxArea([]int{1, 8, 6, 2, 5, 4, 8, 3, 7}))
}
func maxArea(height []int) int {
lenth := len(height)
maxArea := 0
leftMaxHeigh := 0
for i := 0; i < lenth; i++ {
leftHigh := height[i]
if leftHigh > leftMaxHeigh {
leftMaxHeigh = leftHigh
for j := i + 1; j < lenth; j++ {
area := leftHigh * (j - i)
if leftHigh > height[j] {
area = height[j] * (j - i)
}
if area > maxArea {
maxArea = area
}
}
}
}
return maxArea
}
方法二:
package main
import (
"fmt"
)
func main() {
fmt.Println(maxArea([]int{1, 8, 6, 2, 5, 4, 8, 3, 7}))
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
func min(a, b int) int {
if a > b {
return b
}
return a
}
func maxArea(height []int) int {
lenth := len(height)
maxArea, left := 0, 0
right := lenth - 1
for left < right {
area := (right - left) * min(height[right], height[left])
maxArea = max(area, maxArea)
if height[right] > height[left] {
left++
} else {
right--
}
}
return maxArea
}