Given N candies and K people. In the first turn, the first person gets 1 candy, the second gets 2 candies, and so on till K people. In the next turn, the first person gets K+1 candies, the second person gets k+2 candies, and so on. If the number of candies is less than the required number of candies at every turn, then the person receives the remaining number of candies.Â
The task is to find the total number of candies every person has at the end.Â
Examples:
Input: N = 7, K = 4Â
Output: 1 2 3 1Â
At the first turn, the fourth people has to be given 4 candies, but there isÂ
only 1 left, hence he takes one only.ÂInput: N = 10, K = 3Â
Output: 5 2 3Â
At the second turn first one receives 4 and then we have no more candies left.
A naive approach is to iterate for every turn and distribute candies accordingly till candies are finished.Â
Time complexity: O(Number of distributions)
A better approach is to perform every turn in O(1) by calculating sum of natural numbers till the last term of series which will be (turns*k) and subtracting the sum of natural numbers till the last term of previous series which is (turns-1)*k. Keep doing this till the sum is less than N, once it exceeds then distribute candies in the given way till possible. We call a turn completed if every person gets the desired number of candies he is to get in a turn.Â
Below is the implementation of the above approach:Â
C++
// C++ code for better approach// to distribute candies#include <bits/stdc++.h>using namespace std;Â
// Function to find out the number of// candies every person receivedvoid candies(int n, int k){Â
    // Count number of complete turns    int count = 0;Â
    // Get the last term    int ind = 1;Â
    // Stores the number of candies    int arr[k];Â
    memset(arr, 0, sizeof(arr));Â
    while (n) {Â
        // Last term of last and        // current series        int f1 = (ind - 1) * k;        int f2 = ind * k;Â
        // Sum of current and last series        int sum1 = (f1 * (f1 + 1)) / 2;        int sum2 = (f2 * (f2 + 1)) / 2;Â
        // Sum of current series only        int res = sum2 - sum1;Â
        // If sum of current is less than N        if (res <= n) {            count++;            n -= res;            ind++;        }        else // Individually distribute        {            int i = 0;Â
            // First term            int term = ((ind - 1) * k) + 1;Â
            // Distribute candies till there            while (n > 0) {Â
                // Candies available                if (term <= n) {                    arr[i++] = term;                    n -= term;                    term++;                }                else // Not available                {                    arr[i++] = n;                    n = 0;                }            }        }    }Â
    // Count the total candies    for (int i = 0; i < k; i++)        arr[i] += (count * (i + 1))                 + (k * (count * (count - 1)) / 2);Â
    // Print the total candies    for (int i = 0; i < k; i++)        cout << arr[i] << " ";}Â
// Driver Codeint main(){Â Â Â Â int n = 10, k = 3;Â Â Â Â candies(n, k);Â
    return 0;} |
Java
// Java code for better approach// to distribute candiesÂ
class GFG {    // Function to find out the number of    // candies every person received    static void candies(int n, int k){        int[] arr = new int[k];        int j = 0;        while(n>0){                         for(int i =0;i<k;i++){                j++;                if(n<=0){                    break;                }                else{                    if(j<n){                        arr[i] = arr[i]+j;                    }                    else{                        arr[i] = arr[i]+n;                    }                    n = n-j;                }                             }        }        for(int i:arr){            System.out.print(i+" ");        }    }            // Driver Code      public static void main(String[] args)      {        int n = 10, k = 3;        candies(n, k);      }    }Â
        // This code is contributed by ihritik |
Python3
# Python3 code for better approach# to distribute candiesimport math as mtÂ
# Function to find out the number of# candies every person receiveddef candies(n, k):Â
    # Count number of complete turns    count = 0Â
    # Get the last term    ind = 1Â
    # Stores the number of candies    arr = [0 for i in range(k)]Â
    while n > 0:Â
        # Last term of last and        # current series        f1 = (ind - 1) * k        f2 = ind * kÂ
        # Sum of current and last series        sum1 = (f1 * (f1 + 1)) // 2        sum2 = (f2 * (f2 + 1)) //2Â
        # Sum of current series only        res = sum2 - sum1Â
        # If sum of current is less than N        if (res <= n):            count += 1            n -= res            ind += 1        else: # Individually distribute            i = 0Â
            # First term            term = ((ind - 1) * k) + 1Â
            # Distribute candies till there            while (n > 0):Â
                # Candies available                if (term <= n):                    arr[i] = term                    i += 1                    n -= term                    term += 1                else:                    arr[i] = n                    i += 1                    n = 0Â
    # Count the total candies    for i in range(k):        arr[i] += ((count * (i + 1)) +                   (k * (count * (count - 1)) // 2))Â
    # Print the total candies    for i in range(k):        print(arr[i], end = " ")Â
# Driver Coden, k = 10, 3candies(n, k)Â
# This code is contributed by Mohit kumar |
C#
// C# code for better approach// to distribute candiesÂ
using System;class GFG{    // Function to find out the number of    // candies every person received    static void candies(int n, int k)    {             // Count number of complete turns        int count = 0;             // Get the last term        int ind = 1;             // Stores the number of candies        int []arr=new int[k];             for(int i=0;i<k;i++)         arr[i]=0;             while (n>0) {                 // Last term of last and            // current series            int f1 = (ind - 1) * k;            int f2 = ind * k;                 // Sum of current and last series            int sum1 = (f1 * (f1 + 1)) / 2;            int sum2 = (f2 * (f2 + 1)) / 2;                 // Sum of current series only            int res = sum2 - sum1;                 // If sum of current is less than N            if (res <= n) {                count++;                n -= res;                ind++;            }            else // Individually distribute            {                int i = 0;                     // First term                int term = ((ind - 1) * k) + 1;                     // Distribute candies till there                while (n > 0) {                         // Candies available                    if (term <= n) {                        arr[i++] = term;                        n -= term;                        term++;                    }                    else // Not available                    {                        arr[i++] = n;                        n = 0;                    }                }            }        }             // Count the total candies        for (int i = 0; i < k; i++)            arr[i] += (count * (i + 1))                     + (k * (count * (count - 1)) / 2);             // Print the total candies        for (int i = 0; i < k; i++)            Console.Write( arr[i] + " ");    }         // Driver Code    public static void Main()    {        int n = 10, k = 3;        candies(n, k);                  }}Â
Â
// This code is contributed by ihritik |
PHP
<?php// PHP code for better approach // to distribute candies Â
// Function to find out the number of // candies every person received function candies($n, $k) { Â
    // Count number of complete turns     $count = 0; Â
    // Get the last term     $ind = 1; Â
    // Stores the number of candies     $arr = array_fill(0, $k, 0) ;         while ($n)     { Â
        // Last term of last and         // current series         $f1 = ($ind - 1) * $k;         $f2 = $ind * $k; Â
        // Sum of current and last series         $sum1 = floor(($f1 * ($f1 + 1)) / 2);         $sum2 = floor(($f2 * ($f2 + 1)) / 2); Â
        // Sum of current series only         $res = $sum2 - $sum1; Â
        // If sum of current is less than N         if ($res <= $n)         {             $count++;             $n -= $res;             $ind++;         }         else // Individually distribute         {             $i = 0; Â
            // First term             $term = (($ind - 1) * $k) + 1; Â
            // Distribute candies till there             while ($n > 0)             { Â
                // Candies available                 if ($term <= $n)                 {                     $arr[$i++] = $term;                     $n -= $term;                     $term++;                 }                 else // Not available                 {                     $arr[$i++] = $n;                     $n = 0;                 }             }         }     } Â
    // Count the total candies     for ($i = 0; $i < $k; $i++)         $arr[$i] += floor(($count * ($i + 1)) + ($k *                          ($count * ($count - 1)) / 2)); Â
    // Print the total candies     for ($i = 0; $i < $k; $i++)         echo $arr[$i], " ";} Â
// Driver Code $n = 10;$k = 3; candies($n, $k);Â
// This code is contributed by Ryuga?> |
Javascript
<script>Â
// JavaScript code for better approach// to distribute candiesÂ
    // Function to find out the number of    // candies every person received    function candies(n , k) {Â
        // Count number of complete turns        var count = 0;Â
        // Get the last term        var ind = 1;Â
        // Stores the number of candies        var arr = Array(k);Â
        for (i = 0; i < k; i++)            arr[i] = 0;Â
        while (n > 0) {Â
            // Last term of last and            // current series            var f1 = (ind - 1) * k;            var f2 = ind * k;Â
            // Sum of current and last series            var sum1 = (f1 * (f1 + 1)) / 2;            var sum2 = (f2 * (f2 + 1)) / 2;Â
            // Sum of current series only            var res = sum2 - sum1;Â
            // If sum of current is less than N            if (res <= n) {                count++;                n -= res;                ind++;            } else // Individually distribute            {                var i = 0;Â
                // First term                var term = ((ind - 1) * k) + 1;Â
                // Distribute candies till there                while (n > 0) {Â
                    // Candies available                    if (term <= n) {                        arr[i++] = term;                        n -= term;                        term++;                    } else // Not available                    {                        arr[i++] = n;                        n = 0;                    }                }            }        }Â
        // Count the total candies        for (i = 0; i < k; i++)            arr[i] += (count * (i + 1)) +            (k * (count * (count - 1)) / 2);Â
        // Print the total candies        for (i = 0; i < k; i++)            document.write(arr[i] + " ");    }Â
    // Driver Code             var n = 10, k = 3;        candies(n, k);Â
// This code contributed by Rajput-Ji Â
</script> |
5 2 3
Â
Time complexity: O(Number of turns + K)
Auxiliary Space: O(k)
An efficient approach is to find the largest number(say MAXI) whose sum upto natural numbers is less than N using Binary search. Since the last number will always be a multiple of K, we get the last number of complete turns. Subtract the summation till then from N. Distribute the remaining candies by traversing in the array.Â
Below is the implementation of the above approach:Â
C++
// C++ implementation of the above approach#include <bits/stdc++.h>using namespace std;Â
// Function to find out the number of// candies every person receivedvoid candies(int n, int k){Â
    // Count number of complete turns    int count = 0;Â
    // Get the last term    int ind = 1;Â
    // Stores the number of candies    int arr[k];Â
    memset(arr, 0, sizeof(arr));Â
    int low = 0, high = n;Â
    // Do a binary search to find the number whose    // sum is less than N.    while (low <= high) {Â
        // Get mide        int mid = (low + high) >> 1;        int sum = (mid * (mid + 1)) >> 1;Â
        // If sum is below N        if (sum <= n) {Â
            // Find number of complete turns            count = mid / k;Â
            // Right halve            low = mid + 1;        }        else {Â
            // Left halve            high = mid - 1;        }    }Â
    // Last term of last complete series    int last = (count * k);Â
    // Subtract the sum till    n -= (last * (last + 1)) / 2;Â
    int i = 0;Â
    // First term of incomplete series    int term = (count * k) + 1;Â
    while (n) {        if (term <= n) {            arr[i++] = term;            n -= term;            term++;        }        else {            arr[i] += n;            n = 0;        }    }Â
    // Count the total candies    for (int i = 0; i < k; i++)        arr[i] += (count * (i + 1))               + (k * (count * (count - 1)) / 2);Â
    // Print the total candies    for (int i = 0; i < k; i++)        cout << arr[i] << " ";}Â
// Driver Codeint main(){Â Â Â Â int n = 7, k = 4;Â Â Â Â candies(n, k);Â
    return 0;} |
Java
// Java implementation of the above approachÂ
class GFG{    // Function to find out the number of    // candies every person received    static void candies(int n, int k)    {             // Count number of complete turns        int count = 0;             // Get the last term        int ind = 1;             // Stores the number of candies        int []arr=new int[k];              for(int i=0;i<k;i++)         arr[i]=0;                   int low = 0, high = n;             // Do a binary search to find the number whose        // sum is less than N.        while (low <= high) {                 // Get mide            int mid = (low + high) >> 1;            int sum = (mid * (mid + 1)) >> 1;                 // If sum is below N            if (sum <= n) {                     // Find number of complete turns                count = mid / k;                     // Right halve                low = mid + 1;            }            else {                     // Left halve                high = mid - 1;            }        }             // Last term of last complete series        int last = (count * k);             // Subtract the sum till        n -= (last * (last + 1)) / 2;             int j = 0;             // First term of incomplete series        int term = (count * k) + 1;             while (n > 0) {            if (term <= n) {                arr[j++] = term;                n -= term;                term++;            }            else {                arr[j] += n;                n = 0;            }        }             // Count the total candies        for (int i = 0; i < k; i++)            arr[i] += (count * (i + 1))                + (k * (count * (count - 1)) / 2);             // Print the total candies        for (int i = 0; i < k; i++)            System.out.print( arr[i] + " " );    }         // Driver Code    public static void main(String []args)    {        int n = 7, k = 4;        candies(n, k);                  }Â
}Â
// This code is contributed by ihritik |
Python3
# Python3 implementation of the above approachÂ
# Function to find out the number of# candies every person receiveddef candies(n, k):Â
    # Count number of complete turns    count = 0;Â
    # Get the last term    ind = 1;Â
    # Stores the number of candies    arr = [0] * k;Â
    low = 0;    high = n;Â
    # Do a binary search to find the     # number whose sum is less than N.    while (low <= high):Â
        # Get mide        mid = (low + high) >> 1;        sum = (mid * (mid + 1)) >> 1;Â
        # If sum is below N        if (sum <= n): Â
            # Find number of complete turns            count = int(mid / k);Â
            # Right halve            low = mid + 1;        else:Â
            # Left halve            high = mid - 1;Â
    # Last term of last complete series    last = (count * k);Â
    # Subtract the sum till    n -= int((last * (last + 1)) / 2);Â
    i = 0;Â
    # First term of incomplete series    term = (count * k) + 1;Â
    while (n):        if (term <= n):            arr[i] = term;            i += 1;            n -= term;            term += 1;        else:            arr[i] += n;            n = 0;Â
    # Count the total candies    for i in range(k):        arr[i] += ((count * (i + 1)) +                int(k * (count * (count - 1)) / 2));Â
    # Print the total candies    for i in range(k):        print(arr[i], end = " ");Â
# Driver Coden = 7;k = 4;candies(n, k);Â
# This code is contributed by chandan_jnu |
C#
// C# implementation of the above approachÂ
using System;class GFG{    // Function to find out the number of    // candies every person received    static void candies(int n, int k)    {             // Count number of complete turns        int count = 0;             // Get the last term        int ind = 1;             // Stores the number of candies        int []arr=new int[k];              for(int i=0;i<k;i++)         arr[i]=0;                   int low = 0, high = n;             // Do a binary search to find the number whose        // sum is less than N.        while (low <= high) {                 // Get mide            int mid = (low + high) >> 1;            int sum = (mid * (mid + 1)) >> 1;                 // If sum is below N            if (sum <= n) {                     // Find number of complete turns                count = mid / k;                     // Right halve                low = mid + 1;            }            else {                     // Left halve                high = mid - 1;            }        }             // Last term of last complete series        int last = (count * k);             // Subtract the sum till        n -= (last * (last + 1)) / 2;             int j = 0;             // First term of incomplete series        int term = (count * k) + 1;             while (n > 0) {            if (term <= n) {                arr[j++] = term;                n -= term;                term++;            }            else {                arr[j] += n;                n = 0;            }        }             // Count the total candies        for (int i = 0; i < k; i++)            arr[i] += (count * (i + 1))                + (k * (count * (count - 1)) / 2);             // Print the total candies        for (int i = 0; i < k; i++)            Console.Write( arr[i] + " " );    }         // Driver Code    public static void Main()    {        int n = 7, k = 4;        candies(n, k);                  }Â
}Â
// This code is contributed by ihritik |
PHP
<?php// PHP implementation of the above approachÂ
// Function to find out the number of// candies every person receivedfunction candies($n, $k){Â
    // Count number of complete turns    $count = 0;Â
    // Get the last term    $ind = 1;Â
    // Stores the number of candies    $arr = array_fill(0, $k, 0);Â
    $low = 0;    $high = $n;Â
    // Do a binary search to find the     // number whose sum is less than N.    while ($low <= $high)     {Â
        // Get mide        $mid = ($low + $high) >> 1;        $sum = ($mid * ($mid + 1)) >> 1;Â
        // If sum is below N        if ($sum <= $n)         {Â
            // Find number of complete turns            $count = (int)($mid / $k);Â
            // Right halve            $low = $mid + 1;        }        else        {Â
            // Left halve            $high = $mid - 1;        }    }Â
    // Last term of last complete series    $last = ($count * $k);Â
    // Subtract the sum till    $n -= (int)(($last * ($last + 1)) / 2);Â
    $i = 0;Â
    // First term of incomplete series    $term = ($count * $k) + 1;Â
    while ($n)     {        if ($term <= $n)         {            $arr[$i++] = $term;            $n -= $term;            $term++;        }        else        {            $arr[$i] += $n;            $n = 0;        }    }Â
    // Count the total candies    for ($i = 0; $i < $k; $i++)        $arr[$i] += ($count * ($i + 1)) +          (int)($k * ($count * ($count - 1)) / 2);Â
    // Print the total candies    for ($i = 0; $i < $k; $i++)        echo $arr[$i] . " ";}Â
// Driver Code$n = 7;$k = 4;candies($n, $k);Â
// This code is contributed// by chandan_jnu?> |
Javascript
<script>// javascript implementation of the above approach   // Function to find out the number of    // candies every person received    function candies(n , k) {Â
        // Count number of complete turns        var count = 0;Â
        // Get the last term        var ind = 1;Â
        // Stores the number of candies        var arr = Array(k).fill(0);Â
        for (i = 0; i < k; i++)            arr[i] = 0;Â
        var low = 0, high = n;Â
        // Do a binary search to find the number whose        // sum is less than N.        while (low <= high) {Â
            // Get mide            var mid = parseInt((low + high) /2);            var sum = parseInt((mid * (mid + 1)) / 2);Â
            // If sum is below N            if (sum <= n) {Â
                // Find number of complete turns                count = parseInt(mid / k);Â
                // Right halve                low = mid + 1;            } else {Â
                // Left halve                high = mid - 1;            }        }Â
        // Last term of last complete series        var last = (count * k);Â
        // Subtract the sum till        n -= (last * (last + 1)) / 2;Â
        var j = 0;Â
        // First term of incomplete series        var term = (count * k) + 1;Â
        while (n > 0) {            if (term <= n) {                arr[j++] = term;                n -= term;                term++;            } else {                arr[j] += n;                n = 0;            }        }Â
        // Count the total candies        for (i = 0; i < k; i++)            arr[i] += (count * (i + 1)) + (k * (count * (count - 1)) / 2);Â
        // Print the total candies        for (i = 0; i < k; i++)            document.write(arr[i] + " ");    }Â
    // Driver Code             var n = 7, k = 4;        candies(n, k);Â
Â
// This code contributed by aashish1995 </script> |
1 2 3 1
Â
Time Complexity: O(log N + K)
Auxiliary Space: O(K) for given K
Distribute N candies among K people in c++:
Approach:
The distribute_candies function takes two integers as input: N, which represents the total number of candies, and K, which represents the number of people. It returns a vector of integers, where the i-th element represents the number of candies distributed to the i-th person.
The function initializes a vector result of K elements with zero candies. It then loops until all N candies have been distributed. In each iteration, it calculates the number of candies to give to the current person (candies_to_give) as the minimum of N and i+1. It then adds candies_to_give to the number of candies distributed to the i-th person in result, and subtracts candies_to_give from N. Finally, it increments i to move to the next person.
C++
#include <iostream>#include <vector>Â
std::vector<int> distribute_candies(int N, int K) {    std::vector<int> result(K, 0); // initialize a vector of K elements with zero candies    int i = 0;    while (N > 0) { // loop until we have no more candies to distribute        int candies_to_give = std::min(N, i+1);        result[i % K] += candies_to_give; // distribute candies to the i-th person        N -= candies_to_give; // subtract the distributed candies from N        i += 1; // move to the next person    }    return result;}Â
int main() {Â Â Â Â int N = 10;Â Â Â Â int K = 3;Â Â Â Â std::vector<int> result = distribute_candies(N, K);Â Â Â Â for (int i = 0; i < K; i++) {Â Â Â Â Â Â Â Â std::cout << result[i] << " ";Â Â Â Â }Â Â Â Â Â Â Â return 0;} |
Java
import java.util.*;Â
public class DistributeCandies {    public static List<Integer> distributeCandies(int N,                                                  int K)    {        List<Integer> result            = new ArrayList<>(Collections.nCopies(                K, 0)); // initialize a list of K elements                        // with zero candies        int i = 0;        while (N > 0) { // loop until we have no more                        // candies to distribute            int candiesToGive = Math.min(N, i + 1);            result.set(                i % K,                result.get(i % K)                    + candiesToGive); // distribute candies                                      // to the i-th person            N -= candiesToGive; // subtract the distributed                                // candies from N            i += 1; // move to the next person        }        return result;    }Â
    public static void main(String[] args)    {        int N = 10;        int K = 3;        List<Integer> result = distributeCandies(N, K);        for (int i = 0; i < K; i++) {            System.out.print(result.get(i) + " ");        }           }} |
Python3
def distribute_candies(N, K):    result = [0] * K # initialize a list of K elements with zero candies    i = 0    while N > 0: # loop until we have no more candies to distribute        candies_to_give = min(N, i+1)        result[i % K] += candies_to_give # distribute candies to the i-th person        N -= candies_to_give # subtract the distributed candies from N        i += 1 # move to the next person    return resultÂ
if __name__ == '__main__':Â Â Â Â N = 10Â Â Â Â K = 3Â Â Â Â result = distribute_candies(N, K)Â Â Â Â for i in range(K):Â Â Â Â Â Â Â Â print(result[i], end=" ")Â Â Â Â # output: 3 3 4 |
C#
using System;using System.Collections.Generic;Â
public class Gfg {    public static List<int> distribute_candies(int N, int K) {        List<int> result = new List<int>(new int[K]); // initialize a list of K elements with zero candies        int i = 0;        while (N > 0) { // loop until we have no more candies to distribute            int candies_to_give = Math.Min(N, i+1);            result[i % K] += candies_to_give; // distribute candies to the i-th person            N -= candies_to_give; // subtract the distributed candies from N            i += 1; // move to the next person        }        return result;    }         public static void Main() {        int N = 10;        int K = 3;        List<int> result = distribute_candies(N, K);        for (int i = 0; i < K; i++) {            Console.Write(result[i] + " ");        }        // output: 3 3 4    }} |
Javascript
// JavaScript equivalent function distribute_candies(N, K) {    let result = Array(K).fill(0); // initialize a list of K elements with zero candies    let i = 0;    while (N > 0) { // loop until we have no more candies to distribute        let candies_to_give = Math.min(N, i+1);        result[i % K] += candies_to_give; // distribute candies to the i-th person        N -= candies_to_give; // subtract the distributed candies from N        i += 1; // move to the next person    }    return result;}Â
let N = 10;let K = 3;let result = distribute_candies(N, K); temp="";for (let i = 0; i < K; i++) {Â Â Â Â temp = temp+result[i]+" ";} console.log(temp); |
5 2 3
The time complexity of this algorithm is O(N), because we need to distribute each of the N candies.
The auxiliary space of this algorithm is O(K), because we use a vector of K elements to store the candies distributed to each person.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!
