Split N powers of 2 into two subsets such that their difference of sum is minimum | Java program to find the minimum difference possible by splitting all powers of 2 up to N into two sets of equal size ; Store the largest ; Form two separate groups ; Initialize the sum for two groups as 0 ; Insert 2 ^ n in the first group ; Calculate the sum of least n / 2 - 1 elements added to the first set ; Sum of remaining n / 2 - 1 elements ; Min difference between the two groups ; Driver Code
import java . lang . Math ; class GFG { public static void MinDiff ( int n ) { int val = ( int ) Math . pow ( 2 , n ) ; int sep = n / 2 ; int grp1 = 0 ; int grp2 = 0 ; grp1 = grp1 + val ; for ( int i = 1 ; i < sep ; i ++ ) grp1 = grp1 + ( int ) Math . pow ( 2 , i ) ; for ( int i = sep ; i < n ; i ++ ) grp2 = grp2 + ( int ) Math . pow ( 2 , i ) ; System . out . println ( Math . abs ( grp1 - grp2 ) ) ; } public static void main ( String args [ ] ) { int n = 4 ; MinDiff ( n ) ; } }