Leetcode 198. House Robber

来源:互联网 发布:java string 换行符 编辑:程序博客网 时间:2024/06/03 21:30

问题描述

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.

Credits:
Special thanks to @ifanchu for adding this problem and creating all test cases. Also thanks to @ts for adding additional test cases.

问题分析:题目要求没有相邻两个数同时被选择的最大总收益。
保留两个数组,一个数组dprob[i]表示在第i个选择的条件下前i个数的最大收益,dpnrob[i]表示第i个不选择的条件下前i个数的最大收益。状态转移矩阵:
dprob[i]=dpnrob[i-1]+nums[i];
dpnrob[i]=max(dprob[i-1],dpnrob[i-1])
代码如下:

    public int rob(int[] nums) {        if(nums==null)            return 0;        int n=nums.length;        if(n==0)            return 0;        int[]dprob=new int[n];        int[]dpnrob=new int[n];        dprob[0]=nums[0];        dpnrob[0]=0;        for(int i=1;i<n;i++){            dprob[i]=dpnrob[i-1]+nums[i];            dpnrob[i]=Math.max(dprob[i-1],dpnrob[i-1]);        }        return Math.max(dprob[n-1],dpnrob[n-1]);    }