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。 举例子{1,2,3,4}, f[i]表示到第i家能偷窃的最大钱数,f[0] = nums[0], f[1] = max(nums[0], nums[1]), f[2]有两种可能,就是只取f[1]或者取f[0] + f[2]. 所以递推公式是:
f[i] = Math.max(f[i - 2] + nums[i], f[i - 1]);

时间复杂度: O(n)
空间复杂度: O(n)

public class Solution {
    public int rob(int[] nums) {
        if (nums.length == 0 || nums == null) {
            return 0;
        }
        int[] f = new int[nums.length];
        f[0] = nums[0];
        if (nums.length == 1) {
            return f[0];
        }
        f[1] = nums[0] > nums[1] ? nums[0] : nums[1];
       
        if (nums.length == 2) {
            return f[1];
        }
        for (int i = 2; i < nums.length; i++) {
            f[i] = Math.max(f[i - 2] + nums[i], f[i - 1]);
        }
        return f[nums.length - 1];
    }
}

空间改进
由递推数组可以看出,并不需要n个空间,所以我们用滚动数组

时间复杂度:O(n)
空间复杂度:O(1)

public class Solution {
    public int rob(int[] nums) {
        if (nums.length == 0 || nums == null) {
            return 0;
        }
        int[] f = new int[3];
        f[0] = nums[0];
        if (nums.length == 1) {
            return f[0];
        }
        f[1] = nums[0] > nums[1] ? nums[0] : nums[1];
       
        if (nums.length == 2) {
            return f[1];
        }
        for (int i = 2; i < nums.length; i++) {
            f[i % 3] = Math.max(f[(i - 2) % 3] + nums[i], f[(i - 1) % 3]);
        }
        return f[(nums.length - 1) % 3];
    }
}

colorfuladventure
4 声望4 粉丝

引用和评论

0 条评论