198. House Robber


Problem

https://leetcode.com/problems/house-robber/

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.

Solution

If you decide to rob house[i], then house[i-1] must be untouched, can't use dp[i-1], use dp[i-2] instead(dp[i-2] + 0).

/**
 * @param {number[]} nums
 * @return {number}
 */
var rob = function(nums) {
    if (!nums || nums.length <= 0) { return 0 }

    //               leave         rob
    // dp[i] = max{ dp[i-1], dp[i-2]+nums[i] }


    var dpi = nums[0] // dp[i]   (dp[0])
    var dp2 = 0       // dp[i-2] (dp[-1])

    for (let i = 1; i < nums.length; i += 1) {
        let dp1 = dpi // dp[i-1]
        dpi = Math.max(dp1, dp2 + nums[i])
        dp2 = dp1
    }

    return dpi
};

results matching ""

    No results matching ""