TIC
The Interns Company

House Robber

MediumAcceptance: 47.3%

Problem Statement

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.

Constraints:

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

Input Format:

  • An integer array nums representing the amount of money in each house

Output Format:

  • Return the maximum amount of money you can rob without alerting the police.

Examples:

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.

Solutions

Dynamic Programming Approach

Time: O(n)
Space: O(n)

Use dynamic programming to calculate the maximum amount that can be robbed up to each house. For each house, decide whether to rob it (and skip the previous house) or skip it.

Optimized Space Approach

Time: O(n)
Space: O(1)

Optimize the space complexity of the dynamic programming approach by only keeping track of the maximum profit for the last two houses.

Algorithm Walkthrough

Example input: nums = [2,7,9,3,1]

Step-by-step execution:

  1. Create a DP array: dp = [0, 0, 0, 0, 0]
  2. Base cases: dp[0] = 2, dp[1] = max(2, 7) = 7
  3. For i=2: dp[2] = max(9 + dp[0], dp[1]) = max(9 + 2, 7) = max(11, 7) = 11
  4. For i=3: dp[3] = max(3 + dp[1], dp[2]) = max(3 + 7, 11) = max(10, 11) = 11
  5. For i=4: dp[4] = max(1 + dp[2], dp[3]) = max(1 + 11, 11) = max(12, 11) = 12
  6. Return dp[4] = 12

Hints

Hint 1
Think about the recurrence relation: What is the maximum profit if you consider only the first house? Only the first and second houses?
Hint 2
For any given house, you have two options: rob it or skip it. If you rob it, you can't rob the adjacent house.
Hint 3
Dynamic programming can be used to build up the solution from simpler cases.

Video Tutorial

Video tutorials can be a great way to understand algorithms visually

Visualization

Visualize the dynamic programming process, showing how the maximum profit is calculated for each house.

Key visualization elements:

  • current house
  • previous max profit
  • current max profit
  • decision made

Implementation Notes

This problem is a classic example of dynamic programming. It's important to understand how to formulate the recurrence relation and identify the base cases.