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.

題目本質(zhì):在House Robber I的基礎(chǔ)上,增加一個考慮:不能同時搶劫第一個和最后一個house。因此,可以分別去掉頭尾的house,然后在子數(shù)組中用I中的方法找到最大和,從頭尾的兩個最大和中再選較大的那個作為最終的輸出。

public class Solution {
    public int rob(int[] nums) {
        if(nums == null || nums.length == 0)
            return 0;
            
        int len = nums.length;
        if(len == 1)
            return nums[0];
        if(len == 2)
            return Math.max(nums[0], nums[1]);
    
        return Math.max(sub_rob(nums,0,len-2), sub_rob(nums,1,len-1));
    }
    
    public int sub_rob(int[] nums, int start, int end){
        int len = end - start + 1;

        int temp0 = 0, temp1 = nums[start];
        int temp = 0;

        for(int i = 1; i < len; i++){
            temp = Math.max(temp0, temp1);
            temp1 = temp0 + nums[start+i];
            temp0 = temp;
        }

        return Math.max(temp0, temp1);
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容