House Robber

https://leetcode.com/problems/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.

Thoughts

数组找最大,想DP. 设f(i)到i时的全局最优解,那么它的值可能为

  1. 不抢劫i,f(i) = f(i - 1)

  2. 抢劫i, 由于题目要求,这时要跳过i-1, 相当于抢劫i-2时的最优解(不用管i-2到底有没有真抢)+上抢劫i的和。

Code

class Solution {
    public int rob(int[] nums) {
        int n = nums.length;
        if (n == 0) {
            return 0;
        } else if (n == 1) {
            return nums[0];
        }

        int[] f = new int[3];
        f[0] = nums[0];
        f[1] = Math.max(nums[1], nums[0]);

        for (int i = 2; i < n; i++) {
            f[i % 3] = Math.max(f[(i - 2) % 3] + nums[i], f[(i - 1) % 3]);
        }

        return f[(n - 1) % 3];
    }
}

Analysis

时间复杂度为一次遍历, O(n).

Last updated