A professional robber is planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping him from robbing each of them is that adjacent houses have security system connected
belongs to collection: Top C++ Dynamic programming problems for interviews
All Answers
total answers (1)

C++ programming
Example
Input: [1,2,3,1] Output: 4 Explanation: Option 1: Rob house 1 (money = 1) and then rob house 3 (money = 3). Total amount he can rob = 1 + 3 = 4. Option 2: Rob house 2 (money = 2) and then rob house 4 (money = 1). Total amount he can rob = 2 + 1 = 3 So, option 1 maximizes the money stolen.Algorithm:
The problem can be cut down to sub-problem of finding whether to rob from ith house or not.
Now, in case of taking decision whether to rob from ith house or not, it completely depends on where the money maximizes. Since, adjacent houses are connected, the robber can't rob two adjacent house. Either he can rob from (i-1)th house or he can rob from ith house after robbing from (i-2)th house. To maximize the money simply find which results in maximum amount. In terms of recursive relation we can write,
This recursive relation ultimately yields to the maximum amount that can be robbed.
We can form our DP matrix and convert the recursive relation in memorization.
Pre-requisite:
A 1D array where mone stashed in houses are stored. Let the array to be money
Steps:
1. Bases case: IF (n==0) Return 0; IF (n==1) Return money[0]; 2. Initialize DP matrix int house[n]; // DP matrix //initialize all elements with their respective money for(int i=0;i<n;i++) house[i]=money[i]; 3. IF there is only one house, then simply rob the money. house[0]=money[0]; 4. IF there is two house rob from the house having maximum amount house[1]=(money[0]>money[1])?money[0]:money[1]; 5. Formulate the recursive function: for(int i=2;i<n;i++){ //for more houses house[i]=max(house[i]+house[i-2],house[i-1]); } //house[i-2]= f(i-2) // as updated by DP matrix // house[i-2]= f(i-2) // as updated by DP matrix // house[i]( on R.H.S) = money of ith house // as not still updated by DP matrix // house[i] (on L.H.S) = f(i) // as it's going to be updated by DP matrix 6. Return house[n-1]Example with explanation:
That gives the maximum amount that can be robbed without breaking the security.
C++ Implementation:
Output
need an explanation for this answer? contact us directly to get an explanation for this answer