Tutorialspoint
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.
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.
Constraints
  • 1 ≤ nums.length ≤ 100
  • 0 ≤ nums[i] ≤ 400
  • You cannot rob two adjacent houses
  • Time Complexity: O(n)
  • Space Complexity: O(1)
ArraysDynamic Programming PwCD. E. Shaw
Editorial

Login to view the detailed solution and explanation for this problem.

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.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

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

Steps to solve by this approach:

 Step 1: Handle base cases - if array is empty return 0, if single element return that element
 Step 2: Initialize two variables: prevMax (max sum excluding previous) and currMax (max sum so far)
 Step 3: Iterate through each house in the array
 Step 4: For current house, calculate maximum between (prevMax + current house value) and currMax
 Step 5: Update prevMax to store the previous currMax value
 Step 6: Update currMax with the calculated maximum from step 4
 Step 7: Return currMax as the final maximum sum of non-adjacent elements

Submitted Code :