I have figured out the logic and the basic test case is running properly on eclipse. However upon submission it fails every test case. The code is:
private static Scanner sc;
public static void main(String[] args) {
// TODO Auto-generated method stub
sc=new Scanner(System.in);
int n=sc.nextInt();
for(int i=0;i<n;i++) {
int size=sc.nextInt();
int[] arr=new int[size];
for(int j=0;j<size;j++) {
arr[j]=sc.nextInt();
}
zeroSum(arr,0,0);
}
sc.close();
}
public static void zeroSum(int[] arr,int si,int sum) {
if(si==arr.length) {
System.out.println(“No”);
return;
}
if(sum==0) {
System.out.println(“Yes”);
return;
}
zeroSum(arr,si+1,sum);
zeroSum(arr,si+1,sum+arr[si]);
}
Failed Every Test Case
I tweaked the code a bit and it is now:private static Scanner sc; public static void main(String[] args) { // TODO Auto-generated method stub sc=new Scanner(System.in); int n=sc.nextInt(); for(int i=0;i<n;i++) { int size=sc.nextInt(); int[] arr=new int[size]; for(int j=0;j<size;j++) { arr[j]=sc.nextInt(); } boolean ans=zeroSum(arr,0,0); if(ans) { System.out.println(“Yes”); }else System.out.println(“No”); } sc.close(); } public static boolean zeroSum(int[] arr,int si,int sum) { if(sum==0) { return true; } if(si==arr.length) { return false; } return zeroSum(arr,si+1,sum)||zeroSum(arr,si+1,sum+arr[si]); }
@Rishabh8488,
https://ide.codingblocks.com/s/241519 corrected code.
Note that the NULL subset ( subset with no elements ) is not to be considered as that would always have sum 0. To avoid considering that , we take a flag variable bool check = false and mark it as true even if we include a single element. Else it remains false. The NULL subset would be the only subset where the flag would remain false. For all other subsets , they would have included atleast one element and hence their flag would be true.
Also your code was giving true for any case because of this.
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.