LeetCode 198
House Robber
Concepts:
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 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.
Brute-force Approach
Recursively calculate the maximum amount that can be robbed from each house. At each house, the robber can either rob the current house and the one two houses before it or only the house before it. Use the recursive formula f(n) = max(f(n - 1), f(n - 2) + nums[n]).
Time: O(2^n)
Space: O(1), O(n) Recursive stack space
Memoization Approach
Use an array as a cache to store the results of sub problems, that is the maximum amount that can be robbed from each house, and use it to avoid recomputation.
Time: O(n)
Space: O(n), O(n) Recursive stack space
Tabulation Approach
To save recursive stack space, use a bottom-up approach. Instead of recursion, use a loop to calculate the maximum amount that can be robbed from each house, storing the results of sub problems in an array.
Time: O(n)
Space: O(n)
Optimal Approach
Since we need only f(n - 1) and f(n - 2), use two variables instead of an entire array to store the maximum amount that can be robbed from the current house and the house before it. Loop through the houses, updating the variables at each step.
Time: O(n)
Space: O(1)