Distribution of a Number in Array within a Range | 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
def distribution ( n , k , l , r , S , Sk ) : NEW_LINE INDENT a = [ 0 ] * n ; NEW_LINE len = k ; NEW_LINE temp , rem , s = 0 , 0 , 0 ; NEW_LINE diff = S - Sk ; NEW_LINE for i in range ( len ) : NEW_LINE INDENT temp = Sk / k ; NEW_LINE rem = Sk % k ; NEW_LINE if ( temp + rem >= l and temp + rem <= r ) : NEW_LINE INDENT a [ i ] = temp ; NEW_LINE DEDENT elif ( temp + rem > r ) : NEW_LINE INDENT a [ i ] = r ; NEW_LINE DEDENT elif ( temp + rem < r ) : NEW_LINE INDENT print ( " - 1" ) ; NEW_LINE return ; NEW_LINE DEDENT Sk = Sk - a [ i ] ; NEW_LINE k = k - 1 ; NEW_LINE DEDENT if ( Sk > 0 ) : NEW_LINE INDENT print ( " - 1" ) ; NEW_LINE return ; NEW_LINE DEDENT if ( len != 0 ) : NEW_LINE INDENT k = n - len ; NEW_LINE for i in range ( len , n ) : NEW_LINE INDENT temp = diff / k ; NEW_LINE rem = diff % k ; NEW_LINE if ( temp + rem >= l and temp + rem <= r ) : NEW_LINE INDENT a [ i ] = temp ; NEW_LINE DEDENT elif ( temp + rem > r ) : NEW_LINE INDENT a [ i ] = r ; NEW_LINE DEDENT elif ( temp + rem < r ) : NEW_LINE INDENT print ( " - 1" ) ; NEW_LINE return ; NEW_LINE DEDENT diff = diff - a [ i ] ; NEW_LINE k = k - 1 ; NEW_LINE DEDENT if ( diff != 0 ) : NEW_LINE INDENT print ( " - 1" ) ; NEW_LINE return ; NEW_LINE DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT print ( int ( a [ i ] ) , end = " ▁ " ) ; NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n , k , l , r , S , Sk = 5 , 3 , 1 , 5 , 13 , 9 ; NEW_LINE distribution ( n , k , l , r , S , Sk ) ; NEW_LINE DEDENT