码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode-House Robber II

时间:2016-08-02 13:41:32      阅读:160      评论:0      收藏:0      [点我收藏+]

标签:

Note: This is an extension of House Robber.

After robbing those houses on that street, the thief has found himself a new place for his thievery so that he will not get too much attention. This time, all houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, the security system for these houses remain the same as for those in the previous street.

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.

Analysis:

First method: consider two cases (a) rob first house, (b) not rob first house. For each case, we calculate two arrays robThis[i] and notRobThis[i], i.e., the max profit we can get with/without robbing ith house, and we always have

robThis[i] = notRobThis[i-1]+nums[i];

notRobThis[i] = max(robThis[i-1], notRobThis[i-1]);

At last, we just compare (a) rob first house case‘s notRobThis[n], (b) not rob first house case‘s robThis[n]. As we are not allowed to rob both of 1st and last houses.

 

Solution:

 1 public class Solution {
 2     public int rob(int[] nums) {
 3         if (nums.length==0) return 0;
 4         if (nums.length==1) return nums[0];
 5 
 6         int rFirstAThis = nums[0];
 7         int rFirstNoThis = 0;
 8         int nrFirstRThis = 0;
 9         int nrFirstNoThis = 0;
10 
11         for (int i=1;i<nums.length;i++){
12             int pre = rFirstAThis;
13             rFirstAThis = rFirstNoThis + nums[i];
14             rFirstNoThis = Math.max(pre,rFirstNoThis);
15 
16             pre = nrFirstRThis;
17             nrFirstRThis = nrFirstNoThis + nums[i];
18             nrFirstNoThis = Math.max(pre,nrFirstNoThis);
19         }
20 
21         return Math.max(rFirstNoThis,nrFirstRThis);
22     }
23 }

Solution 2:

We can just exclude 1st house / last house and do house robber I twice, and compare the results.

Actually the same idea, but different implementation.

LeetCode-House Robber II

标签:

原文地址:http://www.cnblogs.com/lishiblog/p/5728820.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!