Tuesday, September 22, 2015

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.
Solution1: dynamic programming
递推公式dp[i] = Math.max(dp[i - 1], dp[i - 2] + nums[i - 1])
public class Solution {
    public int rob(int[] nums) {
        if (nums == null || nums.length == 0) {
            return 0;
        }
        
        int len = nums.length;
        int[] dp = new int[len + 1];
        dp[0] = 0;
        dp[1] = nums[0];
        
        for (int i = 2; i <= len; i++) {
            dp[i] = Math.max(dp[i - 1], dp[i - 2] + nums[i - 1]);
        }
        
        return dp[len];
    }
}
Solution2: time complexity is O(n), constant space.
Use two pointers (even, odd) to track maximum value.
public class Solution {
    public int rob(int[] nums) {
        if (nums == null || nums.length == 0) {
            return 0;
        }
        
        int even = 0;
        int odd = 0;
        
        for (int i = 0; i < nums.length; i++) {
            if (i % 2 == 0) {
                even += nums[i];
                if (even < odd) {
                    even = odd;
                }
            } else {
                odd += nums[i];
                if (odd < even) {
                    odd = even;
                }
            }
        }
        
        if (even > odd) {
            return even;
        } else {
            return odd;
        }
    }
}
Reference: http://www.programcreek.com/2014/03/leetcode-house-robber-java/

No comments:

Post a Comment