Given an array of positive integers, which is the most efficient way to find if there exists a sub-array (not necessarily continuous) such that the sum of its elements is equal to a given number k
.
My approach was a naive recursive one:
#include <iostream>
#include <algorithm>
#include <utility>
#include <stdio.h>
#include <queue>
#include <climits>
#include <malloc.h>
#include <stdlib.h>
#include <cstring>
#include <cmath>
#include <sstream>
#include <map>
#include <stack>
#include <string>
#include <ctime>
using namespace std;
int flag=0;
void solve(int ind,int n,int arr[],int sum,int k)
{
if(sum>k)
return;
if(sum==k){
flag++;
return;
}
for(int i=ind+1;i<n;i++)
solve(i,n,arr,sum+arr[i],k);
}
int main()
{
int t;
cin >> t;//number of test cases
while(t--)
{
int n,k;//n->number of array elements
cin >> n >> k;//k->given number
int arr[n];
for(int i=0;i<n;i++)
cin >> arr[i];
for(int i=0;i<n;i++)
solve(i,n,arr,arr[i],k);
if(flag>0)
cout << "YES!" << endl;
else
cout << "NO!" << endl;
flag=0;
}
return 0;
}