80. House Robber[중간]
15 Sep 2020 | Daily Algorithms
Step 1:- [Defining the States of DP]
Here state of dp[ i ] is maximum amount that can be robbed from 0 to i-th houses and at the same time i-th house must be robbed.
Step 2:- [Identifing the Base Case for the solution]
Initializing dp[ 0 ], dp[ 1 ], dp[ 2 ] values.
Step 3 :- [Identifing the Relation between the dp States and framing an Equation]
//robbing i-th house can be done by 2 case,
case 1 : just neglecting i-1 th house and rob i-th house (neglecting last one house) OR
case 2 : neglecting both i-1 th house, i-2 th house and rob i-th house (neglecting last 2 houses)
dp[ i ] = max( dp[ i - 2 ], dp[ i - 3 ] ) + nums[ i ] ;
BECAUSE
for example consider 100,1,2,100.
then answer = (100 + 100) 0-th and 3-rd houses are robbed.
for robbing 3rd house (i.e for dp[ 3 ]) ,here, neglecting last 2 houses leads to answer[200].
class Solution {
public:
int rob(vector<int>& nums) {
int n=nums.size();
if(n==0) return 0; //if their are no houses
else if(n==1) return nums[0]; //only one house
else if(n==2) return max(nums[0],nums[1]); //only two houses
int dp[n]; //for more than two houses
dp[0]=nums[0]; dp[1]=nums[1]; dp[2]=nums[0]+nums[2];
for(int i=3;i<n;i++)
{
if(dp[i-2]>dp[i-3]) //neglecting only 1 previous house.
dp[i] = dp[i-2] + nums[i];
else //neglecting previous 2 houses (as explained in example).
dp[i] = dp[i-3] + nums[i];
}
return max(dp[n-1],dp[n-2]);
}
};
Step 1:- [Defining the States of DP]
Here state of dp[ i ] is maximum amount that can be robbed from 0 to i-th houses and at the same time i-th house must be robbed.
Step 2:- [Identifing the Base Case for the solution]
Initializing dp[ 0 ], dp[ 1 ], dp[ 2 ] values.
Step 3 :- [Identifing the Relation between the dp States and framing an Equation]
//robbing i-th house can be done by 2 case,
case 1 : just neglecting i-1 th house and rob i-th house (neglecting last one house) OR case 2 : neglecting both i-1 th house, i-2 th house and rob i-th house (neglecting last 2 houses)
dp[ i ] = max( dp[ i - 2 ], dp[ i - 3 ] ) + nums[ i ] ;
BECAUSE for example consider 100,1,2,100. then answer = (100 + 100) 0-th and 3-rd houses are robbed. for robbing 3rd house (i.e for dp[ 3 ]) ,here, neglecting last 2 houses leads to answer[200].
class Solution {
public:
int rob(vector<int>& nums) {
int n=nums.size();
if(n==0) return 0; //if their are no houses
else if(n==1) return nums[0]; //only one house
else if(n==2) return max(nums[0],nums[1]); //only two houses
int dp[n]; //for more than two houses
dp[0]=nums[0]; dp[1]=nums[1]; dp[2]=nums[0]+nums[2];
for(int i=3;i<n;i++)
{
if(dp[i-2]>dp[i-3]) //neglecting only 1 previous house.
dp[i] = dp[i-2] + nums[i];
else //neglecting previous 2 houses (as explained in example).
dp[i] = dp[i-3] + nums[i];
}
return max(dp[n-1],dp[n-2]);
}
};
Comments