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.

解题思路1:DP

显然这是一道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;
}

解题思路2:把所有的房子分为奇数家和偶数家,每次交替偷一家。 空间复杂度可以是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);
}

results matching ""

    No results matching ""