mirror of
https://github.com/halfrost/LeetCode-Go.git
synced 2025-07-06 01:15:57 +08:00
24 lines
450 B
Go
24 lines
450 B
Go
package leetcode
|
|
|
|
func trap(height []int) int {
|
|
res, left, right, maxLeft, maxRight := 0, 0, len(height)-1, 0, 0
|
|
for left <= right {
|
|
if height[left] <= height[right] {
|
|
if height[left] > maxLeft {
|
|
maxLeft = height[left]
|
|
} else {
|
|
res += maxLeft - height[left]
|
|
}
|
|
left++
|
|
} else {
|
|
if height[right] >= maxRight {
|
|
maxRight = height[right]
|
|
} else {
|
|
res += maxRight - height[right]
|
|
}
|
|
right--
|
|
}
|
|
}
|
|
return res
|
|
}
|