
Problem
Solution
Submissions
House Robber
Certification: Intermediate Level
Accuracy: 0%
Submissions: 0
Points: 10
Write a JavaScript program to find the maximum sum of non-adjacent elements in an array representing money in houses. You are a robber planning to rob houses along a street, but you cannot rob two adjacent houses because it will trigger an alarm system.
Example 1
- Input: nums = [2, 1, 4, 9]
- Output: 11
- Explanation:
- We can rob house 0 (money = 2) and house 2 (money = 4) for total = 6.
- We can rob house 1 (money = 1) and house 3 (money = 9) for total = 10.
- We can rob house 0 (money = 2) and house 3 (money = 9) for total = 11.
- The maximum sum is 11 by robbing houses 0 and 3.
- We can rob house 0 (money = 2) and house 2 (money = 4) for total = 6.
Example 2
- Input: nums = [2, 7, 9, 3, 1]
- Output: 12
- Explanation:
- We can rob house 0 (money = 2), house 2 (money = 9), and house 4 (money = 1) for total = 12.
- We can rob house 1 (money = 7) and house 3 (money = 3) for total = 10.
- Other combinations yield lower sums.
- The maximum sum is 12.
- We can rob house 0 (money = 2), house 2 (money = 9), and house 4 (money = 1) for total = 12.
Constraints
- 1 ≤ nums.length ≤ 100
- 0 ≤ nums[i] ≤ 400
- You cannot rob two adjacent houses
- Time Complexity: O(n)
- Space Complexity: O(1)
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Use dynamic programming approach to solve this problem
- For each house, decide whether to rob it or not based on maximum profit
- If you rob current house, add previous non-adjacent maximum to current value
- If you don't rob current house, take the maximum up to previous house
- Keep track of maximum sum including and excluding current house