198. House Robber

Description

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.

Solution

DP, time O(n), space O(1)

簡單的dp題。如果用dp[n][2]表示每個房子rob與否,那么:
dp[i][0] = max(dp[i - 1][0], dp[i - 1][1]); // if don't rob i
dp[i][1] = num[i] + dp[i - 1][0] // if rob i
這樣其實可以簡單的降到O(1)空間,存儲兩個值即可。

class Solution {
    public int rob(int[] nums) {
        int ifRobbedPrev = 0;
        int ifDidntRobPrev = 0;
        
        for (int i = 0; i < nums.length; ++i) {
            int tmp = ifDidntRobPrev;
            ifDidntRobPrev = Math.max(ifDidntRobPrev, ifRobbedPrev);
            ifRobbedPrev = nums[i] + tmp;
        }
        
        return Math.max(ifRobbedPrev, ifDidntRobPrev);
    }
}
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容