I know this code/logic is wrong for solving the subset sum problem, but can't seem to understand why.
Calculate the sum of all possible subsets and check if any is equal to the required sum. This would be done in O(n^2) which is obviously wrong as I can solve this via DP O(n*sum).
Thank you.
int main() {
long long int t,n,i,j;
scanf("%lld",&t);
while(t--)
{
long long int p[1005][1005],s[1005][1005]={0};
long long int a[1005],sum;
long long int counter=0;
scanf("%lld %lld",&n,&sum);
for(i=0;i<n;i++)
scanf("%lld",&a[i]);
s[0][0]=a[0];
for(i=0;i<n;i++)
{
for(j=i;j<n;j++)
{
if(i==j)
{
s[i][j]=a[i];
}
else
{
s[i][j]=a[j]+s[i][j-1];
}
}
}
int flag=0;
for(i=0;i<n;i++)
{
for(j=i;j<n;j++)
{
if(s[i][j]==sum)
flag++;
}
}
if(flag)
cout<<1<<endl;
else
cout<<0<<endl;
}
return 0;
}