方法一
暴力求解
package main
import (
"fmt"
)
func main() {
numbers := []int{1,7,3,2,4,5,8,2,7};
result := maxArea(numbers)
fmt.Println(result)
}
func maxArea( height []int ) int {
// write code here
if(len(height) < 2) {
return 0
}
maxCount,h := 0,0
for i,h1 := range height {
for j,h2 := range height {
if(i>=j) {
continue
}
h = h1
if h1 > h2 {
h = h2
}
if h * (j - i) > maxCount {
maxCount = h * (j - i)
}
}
}
return maxCount;
}
方法二
双指针,夹逼
package main
import (
"fmt"
)
func main() {
numbers := []int{1,7,3,2,4,5,8,2,7};
result := maxArea(numbers)
fmt.Println(result)
}
func maxArea( height []int ) int {
// write code here
if(len(height) < 2) {
return 0
}
l, r, h := 0,len(height) - 1, 0
maxCount := 0
for l < r {
h = height[l]
if height[l] > height[r] {
h = height[r]
}
if (r - l) * h > maxCount {
maxCount = (r - l) * h
}
if height[l] > height[r] {
r--
} else {
l++
}
}
return maxCount;
}