美文网首页
198. House Robber

198. House Robber

作者: 衣介书生 | 来源:发表于2018-04-08 21:10 被阅读4次

    题目分析

    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.

    这道题目是一道典型得动态规划题,状态转移方程为 max[i] = max(max[i - 2] + a[i], max[i - 1])
    参考

    代码

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

    相关文章

      网友评论

          本文标题:198. House Robber

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