712427. Candy

Hard

Here is a detailed Markdown blog post for the "Candy" problem:

Candy

Summary

The problem is about distributing candies among children, where each child has a specific preference for the colors of candies they like. The goal is to distribute the candies such that every child gets at least one candy of their preferred color and the total number of candies given out is minimized.

Key concepts involved include arrays, greedy algorithms, and data structures.

Detailed Explanation

The problem involves distributing candies among children, where each child has a specific preference for the colors of candies they like. The goal is to distribute the candies such that every child gets at least one candy of their preferred color and the total number of candies given out is minimized.

To solve this problem, we can use a greedy algorithm approach. We will start by sorting the children in decreasing order of the number of their preferred colors. Then, we will iterate over the sorted list of children, giving each child at least one candy of their preferred color and minimizing the total number of candies given out.

Here is the step-by-step breakdown of the solution:

  1. Sort the children in decreasing order of the number of their preferred colors.
  2. Initialize a variable candiesGiven to 0, which will keep track of the total number of candies given out.
  3. Iterate over the sorted list of children:
    • For each child, find the number of their preferred colors that have not been given out yet.
    • Give at least one candy of their preferred color and update candiesGiven accordingly.
    • If there are no more candies left, break out of the loop.
  4. Return the total number of candies given out.

Time complexity: O(n log n) due to sorting, where n is the number of children. Space complexity: O(1), as we only need a constant amount of space to store the candiesGiven variable.

Optimized Solutions

Java

View on GeeksforGeeks
public class Candy {
    public static int distributeCandy(int[] preferences) {
        Arrays.sort(preferences);
        int candiesGiven = 0;
        for (int preference : preferences) {
            if (preference > 0) {
                candiesGiven += preference;
            } else {
                break;
            }
        }
        return candiesGiven;
    }
}

DevExCode

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

© 2026 DevExCode. All rights reserved.