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ǔ)上,增加一個(gè)考慮:不能同時(shí)搶劫第一個(gè)和最后一個(gè)house。因此,可以分別去掉頭尾的house,然后在子數(shù)組中用I中的方法找到最大和,從頭尾的兩個(gè)最大和中再選較大的那個(gè)作為最終的輸出。

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)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

  • **2014真題Directions:Read the following text. Choose the be...
    又是夜半驚坐起閱讀 11,261評(píng)論 0 23
  • This is an extension of House Robber.After robbing those ...
    ShutLove閱讀 362評(píng)論 0 0
  • Note: This is an extension of House Robber.After robbing ...
    六尺帳篷閱讀 430評(píng)論 0 1
  • 我今天的晚飯是兩個(gè)饅頭加一碗辣椒:大蔥、雞蛋、青辣椒。 綠油油的辣椒配以嫩黃的雞蛋,辣得人直流眼淚,香得我直流口水...
    浮生碎言閱讀 344評(píng)論 0 1
  • 和服,日本最具代表性的服裝。女式和服色彩豐富,不同年齡段各有特點(diǎn),年輕女子喜歡花色鮮艷、彰顯個(gè)性的和服,年長(zhǎng)女性?xún)A...
    豬桐閱讀 649評(píng)論 2 4

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