Tutorialspoint
Problem
Solution
Submissions

House Robber

Certification: Intermediate Level Accuracy: 0% Submissions: 0 Points: 15

Write a C program to find the maximum sum of non-adjacent elements in an array. You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. The constraint is that adjacent houses have security systems connected, so you cannot rob two adjacent houses.

Example 1
  • Input: arr[] = {2, 1, 4, 9}
  • Output: 11
  • Explanation: We can rob house 0 (amount = 2) and house 2 (amount = 4) and house 3 (amount = 9). But we cannot rob house 2 and 3 together as they are adjacent. Maximum sum = 2 + 9 = 11 (rob house 0 and house 3).
Example 2
  • Input: arr[] = {5, 2, 3, 9, 8, 4}
  • Output: 19
  • Explanation: We can rob houses at indices 0, 2, and 5 (Sum = 5 + 3 + 4 = 12), or rob houses at indices 0, 3, 5 (Sum = 5 + 9 + 4 = 18), or rob houses at indices 1, 3, 5 (Sum = 2 + 9 + 8 = 19). Maximum sum is 19.
Constraints
  • 1 ≤ n ≤ 100
  • 0 ≤ arr[i] ≤ 1000
  • 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
  • If you rob current house, you cannot rob the previous house
  • If you don't rob current house, take the maximum from previous calculations
  • Keep track of maximum sum including and excluding current element
  • Return the maximum of both values at the end

Steps to solve by this approach:

 Step 1: Handle base cases - empty array and single element array
 Step 2: Initialize variables to track maximum sum including and excluding previous element
 Step 3: Iterate through the array starting from second element
 Step 4: For each element, calculate new maximum excluding current element
 Step 5: Calculate maximum including current element (previous exclusion + current element)
 Step 6: Update exclusion value for next iteration
 Step 7: Return maximum of inclusion and exclusion values

Submitted Code :