Divide 1 to n into two groups with minimum sum difference | Java program to divide n integers in two groups such that absolute difference of their sum is minimum ; To print vector along size ; Print vector size ; Print vector elements ; To divide n in two groups such that absolute difference of their sum is minimum ; Find sum of all elements upto n ; Sum of elements of group1 ; If sum is greater then or equal to 0 include i in group1 otherwise include in group2 ; Decrease sum of group1 ; Print both the groups ; Driver code
import java . io . * ; import java . util . * ; class GFG { static void printVector ( Vector < Integer > v ) { System . out . println ( v . size ( ) ) ; for ( int i = 0 ; i < v . size ( ) ; i ++ ) System . out . print ( v . get ( i ) + " ▁ " ) ; System . out . println ( ) ; } static void findTwoGroup ( int n ) { int sum = n * ( n + 1 ) / 2 ; int group1Sum = sum / 2 ; Vector < Integer > group1 = new Vector < Integer > ( ) ; Vector < Integer > group2 = new Vector < Integer > ( ) ; for ( int i = n ; i > 0 ; i -- ) { if ( group1Sum - i >= 0 ) { group1 . add ( i ) ; group1Sum -= i ; } else { group2 . add ( i ) ; } } printVector ( group1 ) ; printVector ( group2 ) ; } public static void main ( String [ ] args ) { int n = 5 ; findTwoGroup ( n ) ; } }