[LeetCode]House Robber

来源:互联网 发布:盛势网络剧08bilibili 编辑:程序博客网 时间:2024/05/28 05:18

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.

题意:在一条街上,有很多房子,房子里面有money,不能抢相连的房子,求抢到最大money。

题解:采用动态规划,如果当前在i为止,dp[i] = max(dp[i-2]+money[i],dp[i-1]),    i=0 ,dp[0]=money[0],dp[1] = max(money[0],money[1]);

code:

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



0 0
原创粉丝点击