198. House Robber

Description of Problem

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 systems connected and it will automatically contact the police if two adjacent houses were broken into on the same night.

Given an integer array nums representing the amount of money of each house, return the maximum amount of money you can rob tonight without alerting the police.

Example 1:

Input: nums = [1,2,3,1]
Output: 4
Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).
Total amount you can rob = 1 + 3 = 4.

Example 2:

Input: nums = [2,7,9,3,1]
Output: 12
Explanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1).
Total amount you can rob = 2 + 9 + 1 = 12.

Constraints:

  • 1 <= nums.length <= 100
  • 0 <= nums[i] <= 400

Solution

Tags: Dynamic Programming

Explanation

Let \(S_i\) be maximum gain when house 0 to house i(inclusively) are available. \[ \begin{align} S_0 & = nums[0] \\ S_1 & = \max(nums[0], nums[1]) \\ S_i & = \max( nums[i] + S_{i-2}, S_{i-1} ) \\ \end{align}
\]

Explanation for the third equation, there are two cases when you consider robbing house i:

  • If we rob house i, house i-1 is not avilable. The gain is the nums[i] plus the previous two maximum gain \(S_{i-2}\).
  • If we do not rob house i, we can only consider house 0 to house i-1.

Code

impl Solution {
    pub fn rob(nums: Vec<i32>) -> i32 {
        let n = nums.len();
        let mut s = vec![0 ; n];
        s[0] = nums[0];

        if n > 1 {
            s[1] = nums[0].max(nums[1]);
        }
        
        for i in 2..n {
            s[i] = s[i-1].max(nums[i] + s[i-2])
        }
        
        return s[n - 1];
    }
}

Complexity

  • n is length of nums

Time Complexity

  • \( S(n) = \Theta(n) \)

Auxiliary Space

  • \( S(n) = O(n) \)