123456789101112131415161718192021222324252627282930313233 |
- package main
- import (
- "fmt"
- )
- func maxInt(x, y int) int {
- if x > y {
- return x
- }
- return y
- }
- // DP? try to understand
- func rob(nums []int) int {
- odd, even := 0, 0
- for i := 0; i < len(nums); i++ {
- // if idx is odd
- if i&1 == 1 {
- // rob this store (+nums[i]), or not (even)
- odd = maxInt(odd+nums[i], even)
- } else {
- // rob this store (+nums[i]), or not (odd)
- even = maxInt(even+nums[i], odd)
- }
- }
- return maxInt(odd, even)
- }
- func main() {
- arr := []int{1, 2, 435, 6543, 31, 43, 543, 21, 532}
- fmt.Println(rob(arr))
- }
|