Thursday, June 1, 2017

198. 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.



Solution:

Method 1: Dynamic Programming

This is a classic dynamic programming problem.

Suppose at any house, we already knows the optimal solution maxProfit[] for the previous houses.

For this particular house i, we have two choices: rob, or not rob.

If we rob this house, the profit is nums[i] +  maxProfit[i - 2].

If we do not rob this house, the profit is maxProfit[i - 1].

Therefore, the max profit at this house i is maxProfit[i] = Math.max(maxProfit[i - 2] + nums[i], maxProfit[i - 1]).

The time complexity is O(n) and the space complexity is O(n).



Code:


public class Solution {
    public int rob(int[] nums) {
        if (nums == null || nums.length == 0) {
            return 0;
        }
        if (nums.length == 1) {
            return nums[0];
        }
        int[] maxProfit = new int[nums.length];
        maxProfit[0] = nums[0];
        maxProfit[1] = Math.max(nums[0], nums[1]);
        for (int i = 2; i < nums.length; i++) {
            maxProfit[i] = Math.max(maxProfit[i - 2] + nums[i], maxProfit[i - 1]);
        }
        return maxProfit[nums.length - 1];
    }
}



Method 2: Optimize using rolling arrays.

The time complexity is O(n) and the space complexity is O(1).



Code:


public class Solution {
    public int rob(int[] nums) {
        if (nums == null || nums.length == 0) {
            return 0;
        }
        if (nums.length == 1) {
            return nums[0];
        }
        int[] maxProfit = new int[2];
        maxProfit[0] = nums[0];
        maxProfit[1] = Math.max(nums[0], nums[1]);
        for (int i = 2; i < nums.length; i++) {
            maxProfit[i % 2] = Math.max(maxProfit[(i - 2) % 2] + nums[i], maxProfit[(i - 1) % 2]);
        }
        return maxProfit[(nums.length - 1) % 2];
    }
}