In this article, We will see how to solve for ” Two Sets CSES Solution “. This problem is from the CSES problem set. This problem is really good and broadens your approach to thinking efficiently and optimally.
Let’s see the Problem Statement.
Problem Statement:
Your task is to divide the numbers 1,2,…,n into two sets of equal sum.
Input
The only input line contains an integer n.
Output
Print “YES”, if the division is possible, and “NO” otherwise.
After this, if the division is possible, print an example of how to create the sets. First, print the number of elements in the first set followed by the elements themselves in a separate line, and then, print the second set in a similar way.
Constraints
- 1≤n≤1061≤n≤106
Example 1
Input:7
Output:YES
4
1 2 4 7
3
3 5 6
Example 2
Input:6
Output:NO
Two Sets CSES Solution in java
//Two Sets CSES Solution in java import java.util.*; import java.lang.*; import java.io.*; public class TwoSets { public static void canPartition(long n) { long sum=0; sum=(n*(n+1))/2; if(sum%2!=0){ System.out.println("NO"); } else{ sum/=2; long c1=0,c2=0; StringBuilder s1=new StringBuilder(); StringBuilder s2=new StringBuilder(); for(long i=n;i>0;i--){ if(sum>=i){ s1.append(i+" "); sum-=i; c1+=1; } else{ s2.append(i+" "); c2+=1; } } System.out.println("YES"); System.out.println(c1); System.out.print(s1); System.out.println(); System.out.println(c2); System.out.print(s2); } } public static void main(String args[]) { Scanner sc=new Scanner(System.in); long n=sc.nextLong(); canPartition(n); } } //Two Sets CSES Solution in java