#include<iostream>
#include<bits/stdc++.h>
using namespace std;
#define ll long long
bool check(int a[], int n, int s)
{
bool dp[n+1][s+1];
for(int i=0;i<n+1;i++)
{
for(int j=0;j<s+1;j++)
{
if(i==0)
dp[i][j] = false;
if(j==0)
dp[i][j] = true;
if(a[i-1]<=j)
dp[i][j] = dp[i-1][j-a[i-1]] || dp[i-1][j];
else
dp[i][j] = dp[i-1][j];
}
}
return dp[n][s];
}
int main()
{
//code
int t;
cin>>t;
while(t--)
{
int n;
cin>>n;
int arr[n];
int s=0;
for(int i=0;i<n;i++){
cin>>arr[i];
s+=arr[i];
}
if(s%2==0)
{
s/=2;
if(check(arr,n,s))
cout<<"YES\n";
else
cout<<"NO\n";
}
else
cout<<"NO\n";
}
return 0;
}
The question is Given a set of numbers, check whether it can be partitioned into two subsets such that the sum of elements in both subsets is same or not.
For a test-case; 4 1 5 11 5 The output will be YES because There exists two subsets such that {1, 5, 5} and {11}.
The above test case is passed but it is showing wrong answer for 8 479 758 315 472 730 101 460 619 The actual answer should be YES but it is showing NO.
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
#define ll long long
bool check(int a[], int n, int s)
{
bool dp[n+1][s+1];
for(int i=0;i<n+1;i++)
{
for(int j=0;j<s+1;j++)
{
if(i==0)
dp[i][j] = false;
else if(j==0)
dp[i][j] = true;
else if(a[i-1]<=j)
dp[i][j] = dp[i-1][j-a[i-1]] || dp[i-1][j];
else
dp[i][j] = dp[i-1][j];
}
}
return dp[n][s];
}
int main()
{
//code
int t;
cin>>t;
while(t--)
{
int n;
cin>>n;
int arr[n];
int s=0;
for(int i=0;i<n;i++){
cin>>arr[i];
s+=arr[i];
}
if(s%2==0)
{
s/=2;
if(check(arr,n,s))
cout<<"YES\n";
else
cout<<"NO\n";
}
else
cout<<"NO\n";
}
return 0;
}
This is the corrected code.