198.go 543 B

123456789101112131415161718192021222324252627282930313233
  1. package main
  2. import (
  3. "fmt"
  4. )
  5. func maxInt(x, y int) int {
  6. if x > y {
  7. return x
  8. }
  9. return y
  10. }
  11. // DP? try to understand
  12. func rob(nums []int) int {
  13. odd, even := 0, 0
  14. for i := 0; i < len(nums); i++ {
  15. // if idx is odd
  16. if i&1 == 1 {
  17. // rob this store (+nums[i]), or not (even)
  18. odd = maxInt(odd+nums[i], even)
  19. } else {
  20. // rob this store (+nums[i]), or not (odd)
  21. even = maxInt(even+nums[i], odd)
  22. }
  23. }
  24. return maxInt(odd, even)
  25. }
  26. func main() {
  27. arr := []int{1, 2, 435, 6543, 31, 43, 543, 21, 532}
  28. fmt.Println(rob(arr))
  29. }