Divide 1 to n into two groups with minimum sum difference | 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 group 1 otherwise include in group2 ; Decrease sum of group1 ; Print both the groups ; Driver Code
< ? php function printVector ( $ v ) { echo count ( $ v ) . " STRNEWLINE " ; for ( $ i = 0 ; $ i < count ( $ v ) ; $ i ++ ) echo $ v [ $ i ] . " ▁ " ; echo " STRNEWLINE " ; } function findTwoGroup ( $ n ) { $ sum = $ n * ( $ n + 1 ) / 2 ; $ group1Sum = ( int ) ( $ sum / 2 ) ; $ group1 ; $ group2 ; $ x = 0 ; $ y = 0 ; for ( $ i = $ n ; $ i > 0 ; $ i -- ) { if ( $ group1Sum - $ i >= 0 ) { $ group1 [ $ x ++ ] = $ i ; $ group1Sum -= $ i ; } else { $ group2 [ $ y ++ ] = $ i ; } } printVector ( $ group1 ) ; printVector ( $ group2 ) ; } $ n = 5 ; findTwoGroup ( $ n ) ; ? >