Leetcode 198. House Robber

作者: ShutLove | 来源:发表于2017-11-18 20:07 被阅读9次

    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];
    }

    相关文章

      网友评论

        本文标题:Leetcode 198. House Robber

        本文链接:https://www.haomeiwen.com/subject/vflyvxtx.html