1. 程式人生 > >213. House Robber II

213. House Robber II

edi 現在 true htm mat class html 代碼 pre

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.

這道題是之前那道House Robber 打家劫舍的拓展,現在房子排成了一個圓圈,則如果搶了第一家,就不能搶最後一家,因為首尾相連了,所以第一家和最後一家只能搶其中的一家,或者都不搶,那我們這裏變通一下,如果我們把第一家和最後一家分別去掉,各算一遍能搶的最大值,然後比較兩個值取其中較大的一個即為所求。那我們只需參考之前的House Robber 打家劫舍中的解題方法,然後調用兩邊取較大值,代碼如下:

public int rob(int[] nums) {
        if (nums == null || nums.length == 0) return 0;
        if (nums.length == 1) return nums[0];
        int robNo = 0, robYes = nums[0];
        for (int i = 1; i < nums.length - 1; i++) {
            int temp = robNo;
            robNo = Math.max(robNo, robYes);
            robYes = temp + nums[i];
        }
        int ans = Math.max(robNo, robYes);
         robNo = 0;
         robYes = nums[1];
        for (int i = 2; i < nums.length; i++) {
            int temp = robNo;
            robNo = Math.max(robNo, robYes);
            robYes = temp + nums[i];
        }
        ans = Math.max(Math.max(robNo, robYes), ans);
        return ans;
        
    }

  

213. House Robber II