Never Two consecutive , Include Exclude technique
/*
Stickler the thief wants to loot money from a society having n houses in a single line.
He is a weird person and follows a certain rule when looting the houses.
According to the rule, he will never loot two consecutive houses. At the same time,
he wants to maximize the amount he loots. The thief knows which house has what amount of money
but is unable to come up with an optimal looting strategy. He asks for your help to find the maximum money
he can get if he strictly follows the rule. Each house has a[i] amount of money present in it.
*/
#include<bits/stdc++.h>
// this is clearly an consec include exclude problem
using namespace std;
int maxsumnotconsec(int a[], int n)
{
int incl=a[0];
int exec=0;
for(int i=1;i<n;i++)
{
int inc_new=exec+a[i];
// we can incude the new element(latest ele) if and only if we have excluded prev ele
int exec_new=max(incl,exec);
// we will exclude curr element if prev was included or prev ele was excluded but still has the max value
exec=exec_new;
incl=inc_new;
}
return max(exec,incl);
// sice we have counted the max when excluding the conseq and also having exec more then conseq
// we will return the max of our counts
}
int main()
{
int t;
cin>>t;
while(t--)
{int n;
cin>>n;
int a[n];
for(int i=0;i<n;i++)
{
cin>>a[i];
}
cout<<maxsumnotconsec(a,n)<<endl;
}
return 0;
}
Stickler the thief wants to loot money from a society having n houses in a single line.
He is a weird person and follows a certain rule when looting the houses.
According to the rule, he will never loot two consecutive houses. At the same time,
he wants to maximize the amount he loots. The thief knows which house has what amount of money
but is unable to come up with an optimal looting strategy. He asks for your help to find the maximum money
he can get if he strictly follows the rule. Each house has a[i] amount of money present in it.
*/
#include<bits/stdc++.h>
// this is clearly an consec include exclude problem
using namespace std;
int maxsumnotconsec(int a[], int n)
{
int incl=a[0];
int exec=0;
for(int i=1;i<n;i++)
{
int inc_new=exec+a[i];
// we can incude the new element(latest ele) if and only if we have excluded prev ele
int exec_new=max(incl,exec);
// we will exclude curr element if prev was included or prev ele was excluded but still has the max value
exec=exec_new;
incl=inc_new;
}
return max(exec,incl);
// sice we have counted the max when excluding the conseq and also having exec more then conseq
// we will return the max of our counts
}
int main()
{
int t;
cin>>t;
while(t--)
{int n;
cin>>n;
int a[n];
for(int i=0;i<n;i++)
{
cin>>a[i];
}
cout<<maxsumnotconsec(a,n)<<endl;
}
return 0;
}
Comments
Post a Comment