Distribute M objects starting from Sth person such that every ith person gets arr [ i ] objects | Java program for the above approach ; 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
import java . io . * ; import java . lang . * ; import java . util . * ; class GFG { static void distribute ( int N , int K , int M , int arr [ ] ) { int distribution [ ] = new int [ N ] ; int ptr = K - 1 ; int 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 ( int i = 0 ; i < N ; i ++ ) { System . out . print ( distribution [ i ] + " ▁ " ) ; } } public static void main ( String [ ] args ) { int arr [ ] = { 2 , 3 , 2 , 1 , 4 } ; int M = 11 , S = 2 ; int N = arr . length ; distribute ( N , S , M , arr ) ; } }