House Robber II

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.

Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.

Solution:


This problem is the extension of House Robber I. 

The first element and the last element cannot appear at the same time. So we need to iterate the array for two times. 

The first round: first element is included, the last element is not included.

The second round : first element is not included, the last element is included.

Compare the two rounds and compute the bigger number.


public class Solution {
    public int rob(int[] nums) {
        if (nums == null || nums.length == 0)
            return 0;
        
        int[] dp1 = new int[nums.length];
        int[] dp2 = new int[nums.length];
        int n = nums.length;
        if (n == 1)
            return nums[0];
        
        if (n == 2)
            return Math.max(nums[0],nums[1]);
       //first element is included, last element is not included
       dp1[0] = 0;
       dp1[1] = nums[0];
       for (int i = 2; i < nums.length; i++) {
           dp1[i] = Math.max(dp1[i - 1], dp1[i - 2] + nums[i - 1]);
       }
       //first element is not included, lase element is included
       dp2[0] = 0;
       dp2[1] = nums[1];
       for (int i = 2; i < nums.length; i++) {
           dp2[i] = Math.max(dp2[i - 1], dp2[i - 2] + nums[i]);
       }
       
       
       return Math.max(dp1[n - 1], dp2[n - 1]);
    }
}



 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章