42.go 746 B

1234567891011121314151617181920212223242526272829303132333435
  1. package main
  2. func trap(height []int) (units int) {
  3. n := len(height)
  4. if n <= 2 {
  5. return 0
  6. }
  7. left, right := 0, n-1 // Bidirection scan is the key!!!
  8. maxLeft, maxRight := height[left], height[right]
  9. for left <= right {
  10. if height[left] <= height[right] { // So left bar would meet right bar
  11. if height[left] > maxLeft {
  12. maxLeft = height[left]
  13. } else {
  14. units += maxLeft - height[left]
  15. }
  16. left++
  17. } else { // Else, right bar would meet left bar
  18. if height[right] > maxRight {
  19. maxRight = height[right]
  20. } else {
  21. units += maxRight - height[right]
  22. }
  23. right--
  24. }
  25. }
  26. return
  27. }
  28. // func main() {
  29. // h := []int{0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1}
  30. // println(trap(h))
  31. // h = []int{}
  32. // println(trap(h))
  33. // }