Max sum no adjacent
PROBLEM :
Given an array of positive numbers, find the maximum sum of a subsequence with the constraint that no 2 numbers in the sequence should be adjacent in the array. So 3 2 7 10 should return 13 (sum of 3 and 10) or 3 2 5 10 7 should return 15 (sum of 3, 5 and 7).
Input:
The first line of input contains an integer T denoting the number of test cases.
The first line of each test case is N,N is the size of array.
The second line of each test case contains N input C[i].
Output:
Print the maximum sum of a subsequence.
Constraints:
1 = T = 80
1 = N = 100
1 = C[i] = 500
Example:
Input:
2
6
5 5 10 100 10 5
4
3 2 7 10
Output:
110
13
------------------------------------------------------------------------------
Simple C++ implementation :
------------------------------------------------------------------------------
#include<iostream>
using namespace std;
int max(int[],int) ;
int main()
{
int a[500],t,no,i,r ;
cin>>t ;
while(t--)
{
cin>>no ;
for(i=0;i<no;i++)
cin>>a[i] ;
r=max(a,no) ;
cout<<r<<endl ;
}
return 0;
}
int max(int a[],int no)
{
int ex_max ,max ,i ,temp ;
ex_max=0 ;
max=a[0] ;
for(i=1;i<no;i++)
{
temp=max ;
max=((ex_max+a[i])>max)?(ex_max+a[i]):max ;
ex_max=temp ;
}
return max ;
}
---------------------------------------------------------------------------------
Given an array of positive numbers, find the maximum sum of a subsequence with the constraint that no 2 numbers in the sequence should be adjacent in the array. So 3 2 7 10 should return 13 (sum of 3 and 10) or 3 2 5 10 7 should return 15 (sum of 3, 5 and 7).
Input:
The first line of input contains an integer T denoting the number of test cases.
The first line of each test case is N,N is the size of array.
The second line of each test case contains N input C[i].
Output:
Print the maximum sum of a subsequence.
Constraints:
1 = T = 80
1 = N = 100
1 = C[i] = 500
Example:
Input:
2
6
5 5 10 100 10 5
4
3 2 7 10
Output:
110
13
------------------------------------------------------------------------------
Simple C++ implementation :
------------------------------------------------------------------------------
#include<iostream>
using namespace std;
int max(int[],int) ;
int main()
{
int a[500],t,no,i,r ;
cin>>t ;
while(t--)
{
cin>>no ;
for(i=0;i<no;i++)
cin>>a[i] ;
r=max(a,no) ;
cout<<r<<endl ;
}
return 0;
}
int max(int a[],int no)
{
int ex_max ,max ,i ,temp ;
ex_max=0 ;
max=a[0] ;
for(i=1;i<no;i++)
{
temp=max ;
max=((ex_max+a[i])>max)?(ex_max+a[i]):max ;
ex_max=temp ;
}
return max ;
}
---------------------------------------------------------------------------------
Comments
Post a Comment