Distribution of a Number in Array within a Range | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; void distribution ( int n , int k , int l , int r , int S , int Sk ) { int a [ 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 ) { cout << " - 1" ; return ; } Sk = Sk - a [ i ] ; k = k - 1 ; } if ( Sk > 0 ) { cout << " - 1" ; return ; } if ( len ) { 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 ) { cout << " - 1" ; return ; } diff = diff - a [ i ] ; k = k - 1 ; } if ( diff ) { cout << " - 1" ; return ; } } for ( int i = 0 ; i < n ; i ++ ) { cout << a [ i ] << " ▁ " ; } } int main ( ) { int n = 5 , k = 3 , l = 1 , r = 5 , S = 13 , Sk = 9 ; distribution ( n , k , l , r , S , Sk ) ; return 0 ; }