2015年10月24日星期六

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.
Solution 1: 0 or n-1, one of them must not be robbed. Use DP and House Robber I solution to calculate [0..n-2] and [1...n-1] then get the max of the two.
 public class Solution {  
   public int rob(int[] nums) {  
     int n=nums.length;  
     if (n==0) return 0;  
     if (n==1) return nums[0];  
     return Math.max(rob(nums,0,n-2),rob(nums,1,n-1));  
   }  
   private int rob(int[] nums, int lo, int hi) {  
     int a=0, b=0;// a rob it, b not rot it  
     for (int i=lo; i<=hi; i++) {  
       if (i==lo) {  
         a=nums[i];  
       }  
       else {  
         int aNext=b+nums[i];  
         b=Math.max(a,b);  
         a=aNext;  
       }  
     }  
     return Math.max(a,b);  
   }  
 }  

没有评论:

发表评论