leetcode 213. House Robber II

leetcode 213. House Robber II

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

 

本题是上一题的扩展,其实就是说第一个和第二个二选一的问题,那么算两次,一次为不选最后一个的时候,一次为不选第一个的时候为多少,最后选最大的

 

 1 public class Solution {
 2     public int rob(int[] nums) {
 3         int n=nums.length;
 4         if (n==0){
 5             return 0;
 6         }
 7         if (n==1) return nums[0];
 8         if (n==2) return Math.max(nums[0], nums[1]);
 9         return Math.max(rob_helper(nums,0,n-1),rob_helper(nums,1,n));
10     }
11 
12     public int rob_helper(int[] nums,int begin,int end) {
13         int max=nums[begin];
14         int max2=0;
15         for (int i=1+begin;i<end;i++){
16             if (nums[i]+max2>max){
17                 int tempmax2=max2;
18                 max2=max;
19                 max=nums[i]+tempmax2;
20             }else {
21                 max2=max;
22             }
23         }
24         return max;
25     }
26 }

 

posted on 2017-07-04 09:15  sure0328  阅读(123)  评论(0)    收藏  举报

导航