Sky
Sky

Reputation: 79

House Robber variation: can rob at most K house

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.

Upvotes: -1

Views: 603

Answers (2)

Anubhav Ranjan
Anubhav Ranjan

Reputation: 11

At each house, you have two choices:

  • Pick the current house: If you rob the current house (wt[idx]), you need to skip the adjacent house, so you call memo for the house at idx - 2.
  • Do not pick the current house: If you skip the current house, you call memo for the house at idx - 1.

Full solution:

class Solution {
    
    public int rob(int[] nums) {
        int n = nums.length;
        int [] mem = new int[n];
        Arrays.fill(mem,-1);
        return memo(nums,n-1,mem);
    }

    private int memo(int[] wt,int idx,int[] mem){
        if(idx < 0)return 0;
        if(mem[idx]!=-1)return mem[idx];
        int pick = wt[idx] + memo(wt,idx-2,mem);
        int notPick = memo(wt,idx-1,mem);
        return mem[idx] = Math.max(pick,notPick);
    }

  
}

Upvotes: 1

amit
amit

Reputation: 178491

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.

Upvotes: 2

Related Questions