Back
Leetcode Problems
Array
1D Array2D Array3D ArrayBinary Search
Strings
1D Array2D Array3D ArrayBinary Search
Trees
Introduction to TreesTree Problems
Dynamic programming
1d dp problems2d dp problems
loading image

Please wait a little bit, we are fetching the blogs from the database ....

Back

title: 'DP problem set-2' topic : 'dynamic-programming' id: 2 description: 'Dynamic programming problem set of 1D dp. problems - House robber and House robber 2' subtopic: ['1d-dp']

DP problem set - 2

Summary for the blog ⌨️⌨️ In this blog of Dynamic programming, we will discuss basic DP problems, we will see the problem solving approach, intuition and the code solution for the problems.

Sl NoLeetcode problems/ AlgorithmsLink
1Maximum sum of non-adjacent elementsProblem 1
2House Robber IIProblem 1

Problem No - 1 [Maximum sum of non-adjacent elements/ House robber]

🧑🏽‍💻 Problem statement

You are given an array/list of ‘N’ integers. You are supposed to return the maximum sum of the subsequence with the constraint that no two elements are adjacent in the given array/list.

Note:

A subsequence of an array/list is obtained by deleting some number of elements (can be zero) from the array/list, leaving the remaining elements in their original order.

Example :

For the array - 2 1 4 9

answer is 11

the sum of 'ARR[0]' and 'ARR[2]' is 6, the sum of 'ARR[1]' and 'ARR[3]' is 10, and the sum of 'ARR[0]' and 'ARR[3]' is 11. So if we take the sum of 'ARR[0]' and 'ARR[3]', it will give the maximum sum of sequence in which no elements are adjacent in the given array/list.

Intuition :-

  • The basic idea is that if we consider a particular element in the sum we can’t take the adjacent element in the sum.
  • Hence we should try out all possible combination and determine the maximum sum among then, trying all possible ways means a recursive way,
  • We will iterate the array in the recursion with a index i from n-1 to 0 th index, where n is the length of the array. at every index we can either include the current element in our sum of exclude it form our sum.
  • The base case would be if we reach index 0 we would return nums[0] (since we reached index 0 and we want to maximize the sum we will consider the element at index 0 as well), else if the index reached is less than 0, we would return 0 (as no more element can be included from the array to the sum),
  • Since the time complexity is 2^n and space complexity if O(n), we would need to optimize it, we will use a technique called memoisation to optimize it.
  • In memoisation we will take a 1D array to store the sum of the processed subsequence, which can be used while computing the sum of other subsequence.
  • you can explore other technique called tabulation as well.
#include <bits/stdc++.h> 
int solve(int i,vector<int> &nums,vector<int>&dp){
    if(i==0){
        return nums[0];
    }
    if(i<0) return 0;

    if(dp[i]!=-1) return dp[i];

    int take =nums[i]+solve(i-2, nums,dp);
    int notake = solve(i-1, nums,dp);

    return dp[i]= max(take,notake);
}
int maximumNonAdjacentSum(vector<int> &nums){
    // Write your code here.
    int n =nums.size();
    vector<int>dp(n,-1);
    return solve(n-1,nums,dp);
}

Problem No - 2 [House Robber II]

🧑🏽‍💻 Problem statement

Mr. X is a professional robber planning to rob houses along a street. Each house has a certain amount of money hidden.

All houses along this street are arranged in a circle. That means the first house is the neighbour of the last one. Meanwhile, adjacent houses have a security system connected, and it will automatically contact the police if two adjacent houses are broken into on the same night.

You are given an array/list of non-negative integers 'ARR' representing the amount of money of each house. Your task is to return the maximum amount of money Mr. X can rob tonight without alerting the police.

Note:

It is possible for Mr. X to rob the same amount of money by looting two different sets of houses. Just print the maximum possible robbed amount, irrespective of sets of houses robbed.

For example:

(i) Given the input array arr[] = 2 the output will be 3 because Mr X cannot rob house 1 (money = 2) and then rob house 3 (money = 2), because they are adjacent houses. So, he’ll rob only house 2 (money = 3)

(ii) Given the input array arr[] = 1 the output will be 4 because Mr X rob house 1 (money = 1) and then rob house 3 (money = 3).

(iii) Given the input array arr[] = 0 the output will be 0 because Mr. X has got nothing to rob.

Intuition :-

  • This is similar to the previous problem, we can’t rob from adjacent houses, and the change is houses are arranged in a circle, hence first and last houses are adjacent.
  • The basic idea in this problem is that if we choose first house then we cant choose the last house, and vice versa.
  • So we will create two vectors first and second, first will store all element in nums except at index 0, and second will store all elements in nums except at index n-1;
  • We would find the maximum sum of both the vectors using the previous problem code and return maximum among them
class Solution {
public:
    int solve(int i, vector<int>& nums, vector<int>& dp) {
        if (i == 0)
            return nums[0];
        if (i < 0)
            return 0;
        if (dp[i] != -1)
            return dp[i];
        int take = nums[i] + solve(i - 2, nums, dp);
        int notake = solve(i - 1, nums, dp);

        return dp[i] = max(notake, take);
    }
    int rob(vector<int>& nums) {
        vector<int> first;
        vector<int> second;
        int n = nums.size();
        vector<int> dp(n, -1);
        if (n == 1)
            return nums[0];
        for (int i = 0; i < n; i++) {
            if (i != 0)
                first.push_back(nums[i]);
            if (i != n - 1)
                second.push_back(nums[i]);
        }

        long long int max1 = solve(n - 2, first, dp);
        dp.assign(dp.size(), -1);
        long long int max2 = solve(n - 2, second, dp);

        return max(max1, max2);
    }
};

: Hey! is your brain fried of this blog? . Well what about a game with me?