AlgoMaster Logo

House Robber

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Recursive Approach

The problem of robbing houses can be thought of as making a choice at each house: either you rob it or you skip it. The base problem is that you cannot rob two consecutive houses.

We can define a recursive function robFrom(int i) which returns the maximum amount of money that can be robbed starting from house i. The decision at each house will be:

  1. Rob the current house i and skip the next house i+1.
  2. Do not rob the current house i and try to rob from house i+1.

This will be a naive solution with exponential time complexity, but it establishes the foundation of the problem.

Code:

2. Memoization (Top-Down DP)

To optimize the recursive approach, we can use memoization to store the results of the subproblems that we've already solved, preventing re-calculation and reducing the time complexity from exponential to linear.

Code:

3. Bottom-Up Dynamic Programming

We can reformulate the problem iteratively using a bottom-up dynamic programming approach. We'll systematically determine the best choice at each house leading up to the final decision.

Code:

4. Optimized Space Dynamic Programming

We can further optimize the space complexity by realizing that at any point, we only need the last two states to make our decision.

Code: