House Robber II in C++

C++Server Side ProgrammingProgramming

Consider, you are a professional robber. And you are planning to rob houses along a street. Each house has a certain amount of money stored. All houses are arranged in a circle. That means the first house is the neighbor of the last house. We have to keep in mind that the adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night. So if we have a list of integers representing the amount of money of each house, determine the maximum amount of money you can rob in one night without alerting the police. So if the array is [1,2,3,1], then the output will be 4.

To solve this, we will follow these steps −

  • We are using one module called solve(), that will take the array, start and end, that will act like below −

  • ans := nums[start]

  • create one table for dynamic programming, that’s name is dp, and size is same as nums size.

  • dp[start] := nums[start]

  • for i := start + 1 to end

    • last := dp[i – 1]

    • lastToLast := 0 when i – 2, otherwise dp[i – 2]

    • dp[i] := maximum of nums[i] + lastToLast and last

    • ans := max of dp[i] and ans

  • return ans

  • Robbing is done like below −

  • n := size of nums

  • if n is zero, then return 0

  • if n = 1, then return nums[0]

  • return maximum of solve(nums, 0, n - 2), solve(nums, 1, n – 1)

Example

Let us see the following implementation to get better understanding −

class Solution {
   public:
   void printVector(vector <int>& v){
      for(int i = 0; i << v.size(); i++)cout << v[i] << " ";
      cout << endl;
   }
   int solve(vector <int>& nums, int start, int end){
         int ans = nums[start];
         vector <int> dp(nums.size());
         dp[start] = nums[start];
         for(int i = start + 1; i <= end; i++){
         int last = dp[i - 1];
         int lastToLast = i - 2 < start? 0 : dp[i - 2];
         dp[i] = max(nums[i] + lastToLast, last);
         ans = max(dp[i], ans);
      }
      return ans;
   }
   int rob(vector<int>& nums) {
      int n = nums.size();
      if(!n)return 0;
      if(n == 1)return nums[0];
      return max(solve(nums, 0, n - 2), solve(nums, 1, n - 1));
   }
};

Input

[1,2,3,5]

Output

7
raja
Published on 05-Feb-2020 10:00:51
Advertisements