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.

解题思路:这个题目的意思就是给定一个数组,如 a=[2,4,2,1,6,7,3,6],相邻的数组元素不能相加,必须隔一个数。定义dp数组,dp[i]表示 i+1处满足题目的和,而dp[i]可以看做是dp[i-2]和dp[i-3]的较大值,加上a[i]得到。那么,就可以从前向后对dp进行计算。
public class Solution {
    public int rob(int[] nums) {
        if(nums.length>2){
            int [] dp = new int[nums.length];
            dp[0]=nums[0];
            dp[1]=nums[1];
            dp[2]=dp[0]+nums[2];
            for(int i=3;i<dp.length;i++){
                dp[i]=Math.max(dp[i-2],dp[i-3])+nums[i];
            }
            int max=dp[0];
            for(int i=0;i<dp.length;i++){
                max=max>dp[i]?max:dp[i];
            }
            return max;
        }else if(nums.length==2){
            return Math.max(nums[0],nums[1]);
        }else if(nums.length==1){
            return nums[0];
        }else{
            return 0;
        }
    }
}

你可能感兴趣的:(LeetCode 198. House Robber)