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.

题目的意思是说数组代表这条街上各个房子中的钱,不能拿相邻房子的钱,问最大能获得的钱是多少?

假设有一个这样的数组:

index: 0  1  2  3  4  5  6  7

value: 4  6  9  7  4  5  7  2

我们新开一个数组cache,cache[ i ] 代表 从0 到 i index 这些房子中所能获得的最多的钱。

假设此时index = 7, 如果我们取了index = 7 的房子的钱nums [ 7 ] ,那么前面的房子的钱只能取cache[5]。(因为不能取相邻的)

如果我们不取index = 7的房子的钱,我们可以取cache[6] 的钱。

所以,我们得到一个计算的公式,cache[ i ] = max( nums[ i ] + cache[ i - 2], cache[ i - 1] )。

同时不要忘了cache的base条件为:cache[ 0 ] = nums[ 0 ] , cache[ 1 ] = max ( nums[ 0 ], nums[ 1 ] )

代码:

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

    private int doRob(int[] nums, int[] cache, int i) {
        int twoBeforeI = cache[i - 2] == -1 ? doRob(nums, cache, i - 2) : cache[i - 2];
        int oneBeforI = cache[i - 1] == -1 ? doRob(nums, cache, i - 1) : cache[i - 1];
        cache[i] = Math.max(twoBeforeI + nums[i], oneBeforI);
        return cache[i];
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值