Published
- 1 min read
House robber problem dynamic programming
House Robber Dynamic Programming Problem
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security systems connected and it will automatically contact the police if two adjacent houses were broken into on the same night.
- Why this is a dp problem - because we are asked to maximise the robbery profit, so somewhere in the code we need to get maximum
- There are 2 paths to take in this problem, if current house is to be robbed or previous house loot needs to be considered(which ever is maximum)
- During recursion we would be able to calculate comparision b/w previous and the other previous house
- The code snippet shows reverse recurssion, starting from n-1 things are calculated till we reach the starting
System.out.println(robber.houseRobber(arr, arr.length-1, dp));
private int houseRobber(int arr[], int n, int dp[]){
if(n < 0) {
return 0;
}
if(dp[n] >=0) { //way of using the saved values
System.out.println("Reusing results : "+ dp[n]);
return dp[n];
}
int result = Math.max(houseRobber(arr, n-2, dp) + arr[n], houseRobber(arr, n-1, dp));
dp[n] = result;
return dp[n];
}