Distribute M objects starting from Sth person such that every ith person gets arr[i] objects

Distribute M objects starting from Sth person such that every ith person gets arr[i] objects
Given an array arr[] consisting of N integers (1-based indexing) and two integers M and S, the task is to distribute M objects among N persons, starting from the position S, such that the ith person gets at most arr[i] objects each time.
Examples:

Input: arr[] = {2, 3, 2, 1, 4}, M = 11, S = 2Output: 1, 3, 2, 1, 4Explanation: The distribution of M (= 11) objects starting from Sth(= 2) person is as follows:
For arr[2](= 3): Give 3 objects to the 2nd person. Now, the total number of objects reduces to (11 – 3) = 8.
For arr[3] (= 2): Give 2 objects to the 3rd person. Now, the total number of objects reduces to (8 – 2) = 6.
For arr[4] (= 1): Give 1 object to the 4th person. Now, the total number of objects reduces to (6 – 1) = 5.
For arr[5] (= 4): Give 4 objects to the 5th person. Now, the total number of objects reduces to (5 – 4) = 1.
For arr[1] (= 1): Give 1 object to the 1st person. Now, the total number of objects reduced to (1 – 1) = 0.
Therefore, the distribution of objects is {1, 3, 2, 1, 4}.
Input: arr[] = {2, 3, 2, 1, 4}, M = 3, S = 4Output: 0 0 0 1 2

Approach: The given problem can be solved by traversing the array from the given starting index S and distribute the maximum objects to each array element. Follow the steps below to solve the given problem:
Initialize an auxiliary array, say distribution[] with all elements as 0 to store the distribution of M objects.
Initialize two variables, say ptr and rem as S and M respectively, to store the starting index and remaining M objects.
Iterate until rem is positive, and perform the following steps:
If the value of rem is at least the element at index ptr i.e., arr[ptr], then increment the value of distribution[ptr] by arr[ptr] and decrement the value of rem by arr[ptr].
Otherwise, increment the distribution[ptr] by rem and update rem equal to 0.
Update ptr equal to (ptr + 1) % N to iterate the given array arr[] in a cyclic manner.

After completing the above steps, print the distribution[] as the resultant distribution of objects.
Below is the implementation of the above approach:

C++

  
#include
using namespace std;
  

void distribute(int N, int K,
                int M, int arr[])
{
    
    
    int distribution[N] = { 0 };
  
    
    
    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++) {         cout