I have a problem statement as follows: 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 system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.
Given a list of non-negative integers representing the amount of money in each house, determine the maximum amount of money you can rob tonight without alerting the police.
I am coding it in Java. I am using Dynamic Programming to solve this problem and the code gives me the correct solution. However, the code is not efficient since I am using recursion and not using memoization to solve the problem. How do I use the concept of memoization into this code to make my code efficient? Here's my code:
class Solution {
public int rob(int[] nums) {
return robmax(nums,nums.length-1);
}
public int robmax(int[] nums,int n) {
int max = 0;
if(nums.length==0) return 0;
if(n==1) return Math.max(nums[0],nums[1]);
if(n==0) return nums[0];
else{
max = Math.max(nums[n]+robmax(nums,n-2),robmax(nums,n-1));
}
return max;
}
}
Also, what is the run time complexity of my algorithm.
memoofnvalues to -1 to denote nothing in the array. The first line in your function should check ifmemo[n]is < 0 and if so, do the work. The last line should returnmemo[n]. Then modify your function to store the computed result inmemo[n]. As for your complexity, I believe your original form isO(phi^n)wherephi=1.618... See a discussion on the Fibonacci series as to why. For the memoized form, try that one yourself.