当青训营遇上码上掘金,主题四攒青豆 双指针法解题。 首先我们要知道在数组的第i个位置能积攒的青豆的最大数量是由左边最高柱子和右边最高柱子中较矮的那一个决定的。i处的青豆数量为积攒青豆的最大数量减去i处高度。所以我们维护两个指针和两个变量来解这道题,时间复杂度为O(n),空间复杂度为O(1).
func GreenBean(height []int) (result int) {
left, right := 0, len(height)-1
leftMax, rightMax := 0, 0
for left < right {
leftMax = max(leftMax, height[left])
rightMax = max(rightMax, height[right])
if height[left] < height[right] {
resutlt += leftMax - height[left]
left++
} else {
result += rightMax - height[right]
right--
}
}
return
}
func max(a, b int) int {
if a > b {
return a
}
return b
}