#198
House Robber
MediumArrayDynamic ProgrammingDynamic ProgrammingArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution uses dynamic programming to build up the maximum amount of money that can be robbed up to each house. By keeping track of the maximum amount robbed up to the previous house and the house before that, we can decide whether to rob the current house or skip it.
⚙️
Algorithm
4 steps- 1Step 1: Create an array dp where dp[i] represents the maximum amount of money that can be robbed from the first i houses.
- 2Step 2: Initialize dp[0] = nums[0] and dp[1] = max(nums[0], nums[1]).
- 3Step 3: Iterate through the houses from the 2nd index to the last, updating dp[i] as max(dp[i-1], dp[i-2] + nums[i]).
- 4Step 4: Return dp[n-1] as the result.
solution.py12 lines
1def rob(nums):
2 if not nums:
3 return 0
4 n = len(nums)
5 if n == 1:
6 return nums[0]
7 dp = [0] * n
8 dp[0] = nums[0]
9 dp[1] = max(nums[0], nums[1])
10 for i in range(2, n):
11 dp[i] = max(dp[i - 1], dp[i - 2] + nums[i])
12 return dp[-1]ℹ
Complexity note: The time complexity is O(n) because we only traverse the list of houses once. The space complexity is O(n) due to the dp array used to store the maximum amounts.
- 1The problem can be solved using dynamic programming by breaking it down into subproblems.
- 2Understanding the relationship between the current house and the previous two houses is crucial.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.