881701. Chocolate Distribution Problem

Easy

Chocolate Distribution Problem

Summary

The chocolate distribution problem involves distributing chocolates to a group of children. The problem requires you to distribute the given number of chocolates among n children such that each child gets at least one piece and no more than m pieces. This is an optimization problem that involves sorting, which makes it relevant for the "Sorting" tag.

Detailed Explanation

To solve this problem, we can use a greedy algorithm. The idea is to first distribute as many chocolates as possible among n children such that each child gets at least one piece and no more than m pieces. Then, distribute any remaining chocolates evenly among the children. This way, every child will have at least one chocolate and no more than m.

Here's a step-by-step breakdown of the solution:

  1. Initialize a variable chocolates_per_child to (m + 1) / n. This is the maximum number of chocolates that can be given to each child.
  2. Distribute min(chocolates, n * chocolates_per_child) chocolates among the children. This will ensure that every child gets at least one chocolate and no more than m.
  3. Calculate the remaining number of chocolates: remaining_chocolates = chocolates - (n * min(chocolates, n * chocolates_per_child)).
  4. Distribute remaining_chocolates / n chocolates among the children. This will ensure that every child gets an equal share of the remaining chocolates.

The time complexity of this solution is O(n) and the space complexity is O(1), where n is the number of children.

Optimized Solutions

Java

View on GeeksforGeeks
public class ChocolateDistribution {
    public static void distributeChocolates(int chocolates, int n, int m) {
        int chocolatesPerChild = (m + 1) / n;
        int distributedChocolates = Math.min(chocolates, n * chocolatesPerChild);
        int remainingChocolates = chocolates - (n * distributedChocolates);
        for (int i = 0; i < n; i++) {
            System.out.println("Child " + (i + 1) + " gets " + distributedChocolates + " chocolates.");
        }
        if (remainingChocolates > 0) {
            int remainingChocolatesPerChild = remainingChocolates / n;
            for (int i = 0; i < n; i++) {
                System.out.println("Child " + (i + 1) + " gets an additional " + remainingChocolatesPerChild + " chocolates.");
            }
        }
    }

    public static void main(String[] args) {
        int chocolates = 15;
        int n = 3;
        int m = 2;
        distributeChocolates(chocolates, n, m);
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.