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.
The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.
Example:
Input: [1,8,6,2,5,4,8,3,7]
Output: 49
思路:
1、定义两个下标索引 beg、end,其中,beg 指向数组的切片的开始索引,end 指向切片的结束位置;
2、当 beg 指向的元素大于end指向的元素时,end–;否则 beg++。在此过程中,记录最大的面积
package main
import (
"fmt"
"math"
)
func main() {
input := []int{1,8,6,2,5,4,8,3,7}
ret := maxArea(input)
fmt.Println(ret)
}
func maxArea(height []int) int {
if len(height) < 2 {
return 0
}
ret := 0
beg := 0
end := len(height) - 1
for ; beg < end; {
tem := math.Min(float64(height[beg]), float64(height[end])) * float64(end - beg)
if int(tem) > ret {
ret = int(tem)
}
if(height[beg] > height[end]){
end--
}else {
beg++
}
}
return ret
}