198. House Robber

package LeetCode_198

/**
 * 198. House Robber
 * https://leetcode.com/problems/house-robber/description/
 * */
class Solution {
    fun rob(nums: IntArray): Int {
        //try dp
        val n = nums.size
        if (n == 0) {
            return 0
        }
        if (n == 1) {
            return nums[0]
        }
        val dp = IntArray(n + 1)
        dp[0] = nums[0]
        dp[1] = Math.max(dp[0], nums[1])
        for (i in 2 until n) {
            dp[i] = Math.max(dp[i - 2] + nums[i], dp[i - 1])
            //println("dp[$i]:${dp[i]}")
        }
        return dp[n - 1]
    }
}

 

posted @ 2020-04-04 21:35  johnny_zhao  阅读(93)  评论(0编辑  收藏  举报