213. House Robber II

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.

class Solution {
    public int rob(int[] nums) {
        int n = nums.length;
        if (n == 0) {return 0;}
        if (n == 1) {return nums[0];}
        if (n == 2) {return Math.max(nums[0],nums[1]);}
        
        int[] dp = new int[n+1];
        //no 1
        dp[0] = 0;
        dp[1] = 0;
        for (int i = 2; i <= n; i++){
            dp[i] = Math.max(dp[i-1], dp[i-2]+nums[i-1]);
        }
        
        int flag1 = dp[n];
        
        dp[0] = 0;
        dp[1] = nums[0];
        
        for (int i = 2; i < n; i++){
            dp[i] = Math.max(dp[i-1], dp[i-2]+nums[i-1]);
        }
          
        int flag2 = dp[n-1];
        
        return Math.max(flag1, flag2);
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀(guān)點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi閱讀 7,425評(píng)論 0 10
  • **2014真題Directions:Read the following text. Choose the be...
    又是夜半驚坐起閱讀 9,834評(píng)論 0 23
  • 避免使用名詞作形容詞 用名詞來(lái)形容名詞是中式英語(yǔ)中常見(jiàn)的現(xiàn)象。看到名詞堆砌的句子很頭疼,就是一堆名詞,搞不清句子到...
    慢慢樹(shù)閱讀 406評(píng)論 0 2
  • 研究生的生活,已經(jīng)一年,研二也開(kāi)始了一月。在這個(gè)分不清南北亦或是東西的樓里,一二樓因?yàn)橛羞\(yùn)動(dòng)員入住而重新粉飾裝修,...
    玥羽璃觴閱讀 313評(píng)論 0 0
  • 你考慮特么差距我們?cè)谧?/div>
    蝸牛讀書(shū)閱讀 157評(píng)論 0 0