House Robber

題目
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.

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 m = nums.length;
        int[] dp = new int[m];

        if(nums.length == 0) return 0;
        if(nums.length == 1) return nums[0];
        if(nums.length == 2) return Math.max(nums[0], nums[1]);
        
        dp[0] = nums[0];
        dp[1] = Math.max(nums[0], nums[1]);
        
        for(int i = 2; i < m; i++) {
            dp[i] = Math.max(dp[i - 1], dp[i - 2] + nums[i]);
        }
        
        return dp[m - 1];
    }
}
class Solution {
    public int rob(int[] nums) {
        int n = nums.length;
        if(n == 0) return 0;
        // Define f[i][0] to mean: max number of coins we can steal from house i...n-1 (if we don't steal from i)
        // Define f[i][1] to mean: max number of coins we can steal from house i...n-1 (if we steal from i)
        
        int[][] f = new int[n][2];
        f[n - 1][0] = 0;
        f[n - 1][1] = nums[n - 1];
        
        for(int i = n - 2; i >= 0; i--) {
            f[i][0] = Math.max(f[i + 1][0], f[i + 1][1]);
            f[i][1] = f[i + 1][0] + nums[i];
        }
        return Math.max(f[0][0], f[0][1]);
    }
}
最后編輯于
?著作權(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)容僅代表作者本人觀(guān)點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi閱讀 7,854評(píng)論 0 10
  • **2014真題Directions:Read the following text. Choose the be...
    又是夜半驚坐起閱讀 11,092評(píng)論 0 23
  • 我也想被溫柔對(duì)待
    thetreesir閱讀 178評(píng)論 0 0
  • 迎親這天,不論新郎還是父母,都不會(huì)象平時(shí)一樣睡到自然醒的。但早晨起來(lái)都有什么事要做呢?請(qǐng)我來(lái)告訴你。 首先應(yīng)該把燈...
    wangfengqun閱讀 614評(píng)論 0 0
  • 帶領(lǐng)團(tuán)隊(duì),一定要學(xué)會(huì)放手,更要對(duì)員工有足夠的信任,要相信每個(gè)人的能力去做應(yīng)該做的事情,管理者只需給予一定的指導(dǎo),...
    伊森田慧慧閱讀 181評(píng)論 0 0

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