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.

Solution

DP, time O(n), space O(1)

简单的dp题。如果用dp[n][2]表示每个房子rob与否,那么:
dp[i][0] = max(dp[i - 1][0], dp[i - 1][1]); // if don't rob i
dp[i][1] = num[i] + dp[i - 1][0] // if rob i
这样其实可以简单的降到O(1)空间,存储两个值即可。

class Solution {
    public int rob(int[] nums) {
        int ifRobbedPrev = 0;
        int ifDidntRobPrev = 0;
        
        for (int i = 0; i < nums.length; ++i) {
            int tmp = ifDidntRobPrev;
            ifDidntRobPrev = Math.max(ifDidntRobPrev, ifRobbedPrev);
            ifRobbedPrev = nums[i] + tmp;
        }
        
        return Math.max(ifRobbedPrev, ifDidntRobPrev);
    }
}

你可能感兴趣的:(198. House Robber)