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.

打家劫舍也要讲专业(干一行爱一行),不能打劫相邻的两家否则会触发警报。

显然这是一道DP题,状态转移方程 dp[i] = max(nums[i] + dp[i-2], dp[i-1])

这样做的时间复杂度O(n),空间复杂度O(n)

public int rob(int[] nums) {
    if (nums.length == 0) {
        return 0;
    }
    if (nums.length == 1) {
        return nums[0];
    }
    if (nums.length == 2) {
        return Math.max(nums[0], nums[1]);
    }
    int[] dp = new int[nums.length];
    dp[0] = nums[0];
    dp[1] = Math.max(nums[0], nums[1]);
    int max = 0;
    for (int i = 2; i < nums.length; i++) {
        dp[i] = Math.max(nums[i] + dp[i-2], dp[i-1]);
        max = Math.max(max, dp[i]);
    }
    return max;
}

其实还可以这样想,把所有的房子分为基数家和偶数家,每次交替偷一家。 时间复杂度可以是O(1)

public int rob(int[] nums) {
   int odd = 0;
   int even = 0;
   for (int i = 0; i < nums.length; i++) {
       if (i % 2 == 0) {
           even = Math.max(nums[i] + even, odd);
       } else {
           odd = Math.max(nums[i] + odd, even);
       }
   }
   return Math.max(odd,even);
}