198.House Robber

Description

You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.

Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police. Example 1:

Input: [1,2,3,1]
Output: 4
Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).
             Total amount you can rob = 1 + 3 = 4.

Example 2:

Input: [2,7,9,3,1]
Output: 12
Explanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1).
             Total amount you can rob = 2 + 9 + 1 = 12.

Tags: Math, String

题意

输入一个整数序列,然后求出任意不相邻的数加起来的最大的和

题解

思路1

找到公式用动态规划 ```sh f(0) = nums[0] f(1) = max(f(0), f(1)) f(2) = max(nums[2] + f(0), f(1)) f(3) = max(nums[3] + f(1), f(2)) . . . f(n) = max(nums[n] + f(n-2), f(n-1))

[5,2,6,3,7,1]

dp[1] = 5
dp[2] = 5
dp[3] = max(dp[1] + nums[3], dp[dp[2]])
      = max(5 + 6, 5) = 11
dp[4] = max(dp[2]+dp[4], dp[3])
      = max(5 + 3, 11) =1
dp[5] = max(dp[3] + nums[5], dp[4])
      = max(11 + 1, 11) = 12
dp[6] = max(dp[4] + nums[6], dp[5])
      = max(11 + 7, 12) = 18         


```go
func rob(nums []int) int {
    nLenghth := len(nums)

    dp := make([][2]int, nLenghth+1)
    for i := 1; i <= nLenghth; i++ {
        dp[i][0] = Max(dp[i-1][0], dp[i-1][1])
        dp[i][1] = nums[i-1] + dp[i-1][0]
    }
    return Max(dp[nLenghth][0], dp[nLenghth][1])
}

思路2

任意不相邻,其实这个数是可以传递的 ```go func rob(nums []int) int { prevNo, prevYes := 0, 0

for _, v := range nums {
    tmp := prevNo
    prevNo = Max(prevNo, prevYes)
    prevYes = v + tmp
}
return Max(prevNo, prevYes)

} ```

结语

如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:awesome-golang-leetcode

results matching ""

    No results matching ""