Find Maximum sum in an array such that no 2 elements are adjacent. In this, 1 more condition was also there that first and last elements should also not be taken together.
If it would have been without the last condition, that is, then I developed the following code wherein I take two variables, incl
and excl
and find out the values. It is as follows:
#include <iostream>
using namespace std;
int main (void)
{
int i,n;
cin>>n;
int arr[100];
for ( i = 0; i < n; i++ )
cin>>arr[i];
int incl,excl,excls;
incl = arr[0];
for ( i = 1; i < n; i++ )
{
if (incl > excl)
excls = incl;
else
excls = excl;
incl = excl + arr[i];
excl = excls;
}
if (incl > excl)
cout<<incl;
else
cout<<excl;
cout<<"\n";
return 0;
}
How can I modify this for that special case? Thanks!
Aucun commentaire:
Enregistrer un commentaire