Leetcode 198. 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.

思路:
动态规划
对于第i个房间来说,可以采取抢或不抢。
如果抢的话,截止到当前房间能获得的最大money等于前i-2个房间最大money和当前房间的money。
如果不抢,截止当当前房间能获得的最大money等于前i-1个房间得到的最大money。
用数组money表示截止到第i个房间能抢到的最大钱数,可以得到递推式:
money[i] = Math.max(money[i-1], money[i-2] + rooms[i-1]) (i从1开始)
money[1] = rooms[0];

public int rob(int[] nums) {
    if (nums == null || nums.length == 0) {
        return 0;
    }
    int[] maxMoney = new int[nums.length+1];
    maxMoney[1] = nums[0];
    for (int i = 2; i <= nums.length; i++) {
        maxMoney[i] = Math.max(maxMoney[i-1], maxMoney[i-2] + nums[i-1]);
    }
    return maxMoney[nums.length];
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容