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.

Example:

Given [3, 8, 4], return 8.

Challenge:

O(n) time and O(1) memory.

Solution:

For any particular house i, we could decide the maximum amount based on the max between

  1. maximum amount for previous house
  2. maximum amount for the one before previous house + current house money

Code:

public class Solution {
    /**
     * @param A: An array of non-negative integers.
     * return: The maximum amount of money you can rob tonight
     */
    public long houseRobber(int[] A) {
        if (A == null || A.length == 0) {
            return 0L;
        }
        int n = A.length;
        long[] f = new long[2];
        f[0] = 0;
        f[1] = A[0];
        for (int i = 2; i <= n; i++) {
            f[i % 2] = Math.max(f[(i - 1) % 2], f[(i - 2) % 2] + A[i - 1]);
        }
        return f[n % 2];
    }
}

results matching ""

    No results matching ""