Distribution of a Number in Array within a Range | Java implementation of the approach ; Function for the distribution of the number ; Distribute the number among k elements ; If there is some remaining sum to distribute ; If there are elements remaining to distribute i . e . ( n - k ) ; Divide the remaining sum into n - k elements ; Print the distribution ; Driver code
class GFG { static void distribution ( int n , int k , int l , int r , int S , int Sk ) { int a [ ] = new int [ n ] ; int len = k , temp , rem , s ; int diff = S - Sk ; for ( int i = 0 ; i < len ; i ++ ) { temp = Sk / k ; rem = Sk % k ; if ( temp + rem >= l && temp + rem <= r ) { a [ i ] = temp ; } else if ( temp + rem > r ) { a [ i ] = r ; } else if ( temp + rem < r ) { System . out . print ( " - 1" ) ; return ; } Sk = Sk - a [ i ] ; k = k - 1 ; } if ( Sk > 0 ) { System . out . print ( " - 1" ) ; return ; } if ( len != 0 ) { k = n - len ; for ( int i = len ; i < n ; i ++ ) { temp = diff / k ; rem = diff % k ; if ( temp + rem >= l && temp + rem <= r ) { a [ i ] = temp ; } else if ( temp + rem > r ) { a [ i ] = r ; } else if ( temp + rem < r ) { System . out . print ( " - 1" ) ; return ; } diff = diff - a [ i ] ; k = k - 1 ; } if ( diff != 0 ) { System . out . print ( " - 1" ) ; return ; } } for ( int i = 0 ; i < n ; i ++ ) { System . out . print ( a [ i ] + " ▁ " ) ; } } public static void main ( String [ ] args ) { int n = 5 , k = 3 , l = 1 , r = 5 , S = 13 , Sk = 9 ; distribution ( n , k , l , r , S , Sk ) ; } }