Go two solutions


  • 0
    Y
    func rob(nums []int) int {
        /* Solution 1
        even, odd := 0, 0
        for i, n := range nums {
            if i%2 == 0 {
                even = max(even + n, odd)
            } else {
                odd = max(odd + n, even)
            }
        }
        return max(even, odd)
        */
        d := [2]int{0, 0}
        for _, n := range nums {
            tmp := d[0]
            d[0] = d[1]
            d[1] = max(tmp + n, d[1])
        }
        return d[1]
    }
    
    func max(a, b int) int {
        if a > b {
            return a
        }
        return b
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.