解题步骤:
代码实现
package top100
import (
"math"
"testing"
)
func TestMaxArea(t *testing.T) {
println(maxArea([]int{1, 8, 6, 2, 5, 4, 8, 3, 7}))
}
// 使用双指针来解决这个问题
func maxArea(height []int) int {
var max float64
//描述: 分为左右指针,初始情况下,左指向第一个元素,右指针指向最后一个元素。
//结束条件,左右指针相等
//中间状态,比较纵坐标,谁小谁移动,维护一下最大值。
left, right := 0, len(height)-1
for left != right {
leftX, leftY, rightX, rightY := left+1, height[left], right+1, height[right]
currentArea := float64(rightX-leftX) * math.Min(float64(leftY), float64(rightY))
if max < currentArea {
max = currentArea
}
if leftY < rightY {
left++
} else {
right--
}
}
return int(max)
}
// 暴力解法超时了
func maxArea2(height []int) int {
var max float64
for i := 0; i < len(height); i++ {
for j := i + 1; j < len(height); j++ {
//1 暴力破解,直接计算所有的值,然后取最大的值。
//定义一个最大值max=0
//两层for循环计算比较最大值。
//|x2-x| *min(y2,y) 最大。
currentArea := math.Abs(float64(j-i)) * math.Min(float64(height[i]), float64(height[j]))
if max < currentArea {
max = currentArea
}
}
}
return int(max)
}