HackerEarth Sum of Numbers problem solution

In this HackerEarth Sum of Numbers problem solution, we have given an array of N elements, check if it is possible to obtain a sum of S, by choosing some (or none) elements of the array and adding them.


HackerEarth Sum of Numbers problem solution


HackerEarth Sum of Numbers problem solution.

#include<bits/stdc++.h>
using namespace std;
#define ll long long int
ll arr[20];
void combinationUtil(ll arr[],ll n,ll r,ll index,ll data[],ll i);
void printCombination(ll arr[], ll n, ll r)
{
ll data[r];
combinationUtil(arr, n, r, 0, data, 0);
}
ll ans,flag;
void combinationUtil(ll arr[], ll n, ll r, ll index, ll data[], ll i)
{
if(index == r)
{
ll sum=0;
for (ll j=0; j<r; j++)//sum up all the items being included in the set
sum+=data[j];
if(sum==ans)//check against sum
flag=1;
return;
}
if (i >= n)//if number of elements exceeds N
return;
data[index] = arr[i];//set element
combinationUtil(arr, n, r, index+1, data, i+1);//item is being included
combinationUtil(arr, n, r, index, data, i+1);//item is not included
}
int main()
{
ll a,b,i,j,num,loop_sum;
int test;
scanf("%d",&test);
while(test--)
{
flag=0;
scanf("%lld",&num);
for(i=0;i<num;i++)
scanf("%lld",&arr[i]);
scanf("%lld",&ans);
for(ll r=0;r<=num;r++)
printCombination(arr,num,r);
if(flag==1)
printf("YES\n");
else
printf("NO\n");
}
}

Second solution

#include <bits/stdc++.h>
using namespace std;

int main()
{
int t;cin>>t;
while(t--){
int n; cin>>n; int a[n+5];
for(int i=0;i<n;i++) cin>>a[i];
int s,i,j; cin>>s;
for(i=0;i<(1<<n);i++){
int x=0;
for(j=0;j<n;j++){
if(i & (1<<j)) x+=a[j];
}
if(x==s){
cout<<"YES\n"; break;
}
}
if(i==(1<<n)) {cout<<"NO\n";}
}
return 0;
}


Post a Comment

0 Comments