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

House Robber II

时间:2017-05-10 14:33:20      阅读:162      评论:0      收藏:0      [点我收藏+]

标签:end   circle   rmi   too   out   att   while   bsp   logs   

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.

Notice This is an extension of House Robber.

Example

nums = [3,6,4], return 6

这题的做法是run两遍House Robber的算法 一遍包含第一个house不包含最后一个 二遍包含最后一个房子不包含第一个房子

实际上cover了三种case:1 含第一个不含最后一个 2 含最后一个不含第一个 3 两个全不包含

 

技术分享
 1 public class Solution {
 2     /**
 3      * @param nums: An array of non-negative integers.
 4      * return: The maximum amount of money you can rob tonight
 5      */
 6     public int houseRobber2(int[] nums) {
 7         // write your code here
 8         if(nums==null||nums.length==0){
 9             return 0;
10         }
11         if(nums.length==1) return nums[0];
12         
13         return Math.max(helper(nums, 0, nums.length-2), helper(nums, 1, nums.length-1));
14     }
15     private int helper(int[] nums, int start, int end){
16         int f1 = 0;
17         int f2 = 0;
18         
19         for(int i=start; i<=end; i++){
20             int temp1 = f1;
21             f1=Math.max(f1, f2+nums[i]);
22             f2=temp1;
23         }
24         return f1;
25     }
26 }
技术分享

House Robber II

标签:end   circle   rmi   too   out   att   while   bsp   logs   

原文地址:http://www.cnblogs.com/xinqiwm2010/p/6835437.html

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