Distribute M objects starting from Sth person such that every ith person gets arr [ i ] objects | Function to find distribution of M objects among all array elements ; Stores the distribution of M objects ; Stores the indices of distribution ; Stores the remaining objects ; Iterate until rem is positive ; If the number of remaining objects exceeds required the number of objects ; Increase the number of objects for the index ptr by arr [ ptr ] ; Decrease remaining objects by arr [ ptr ] ; Increase the number of objects for the index ptr by rem ; Decrease remaining objects to 0 ; Increase ptr by 1 ; Print the final distribution ; Driver Code
function distribute ( N , K , M , arr ) { let distribution = new Array ( N ) for ( let i = 0 ; i < N ; i ++ ) { distribution [ i ] = 0 } let ptr = K - 1 ; let rem = M ; while ( rem > 0 ) { if ( rem >= arr [ ptr ] ) { distribution [ ptr ] += arr [ ptr ] ; rem -= arr [ ptr ] ; } else { distribution [ ptr ] += rem ; rem = 0 ; } ptr = ( ptr + 1 ) % N ; } for ( let i = 0 ; i < N ; i ++ ) { document . write ( distribution [ i ] + " " ) } } let arr = [ 2 , 3 , 2 , 1 , 4 ] ; let M = 11 , S = 2 ; let N = arr . length distribute ( N , S , M , arr ) ;