How can we solve the famous House Robber problem if we add the new constrain: The robber can rob at most k houses in total?
Problem Description: 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.
Given an integer array nums representing the amount of money of each house, return the maximum amount of money you can rob tonight without alerting the police.
Example 1:
Input: nums = [1,2,3,1] Output: 4 Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3). Total amount you can rob = 1 3 = 4.
CodePudding user response:
The original problem can be solved using Dynamic Programming by following the recusive formula:
D(i) = max{ D(i-2) value[i] , D(i-1) }
^ ^
rob house i don't rob house i
By adding an additional dimension for the maximal number of houses you can rob, you can easily modify the solution:
D(i, k) = max { D(i-2, k-1) value[i], D(i-1, k) }
And of course, need to add a stop clause when k < 0
The additional dimension will however increase time complexity by a factor of k
.