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);
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容