Distribute candies among children

Last Updated : 6 Sep, 2025

Given an array arr[] where each element represents the rating of a child, find the minimum number of candies required to distribute among all children under the following conditions:

  • Every child must receive at least one candy.
  • A child with a higher rating than their immediate neighbor(s) must receive more candies than that neighbor.

Examples:

Input: arr[] = [1, 2, 3, 4, 5]
Output: 15
Explanation: According to the rule, if a child’s rating is greater than the neighbor, he must get more candy than the neighbor.
Child 0 → rating 1 → gets 1 candy
Child 1 → rating 2 → greater than 1 → gets 2 candies
Child 2 → rating 3 → greater than 2 → gets 3 candies
Child 3 → rating 4 → greater than 3 → gets 4 candies
Child 4 → rating 5 → greater than 4 → gets 5 candies
Total candies are 1 + 2 + 3 + 4 + 5 = 15.

Input: arr[] = [9, 9, 9, 9]
Output: 4
Explanation: No child has a strictly greater rating than the neighbor. So, each child only needs the minimum 1 candy.

Try It Yourself
redirect icon

[Approach 1] Greedy Approach with Dual Traversal - O(n) Time and O(n) Space

We need to ensure each student has more candies than both of their neighbors if their score is higher.

To handle the left neighbor, we traverse left → right: if a student’s score is higher than the one on the left, give them more candies.

To handle the right neighbor, we traverse right → left: if a student’s score is higher than the one on the right, give them more candies.

Finally, for each student we take the sum of maximum from both passes.

Why does taking the maximum work?

Every student must satisfy both neighbors:

  • The left-to-right pass ensures fairness with the left neighbor (if a student has a higher score, they get more candies).
  • The right-to-left pass ensures fairness with the right neighbor.

But a student might need more candies to satisfy one side than the other. To keep the rule valid in both directions at once, we give them the maximum of the two counts. This way, no student violates the rule with either neighbor, while still keeping the distribution minimal.

C++
#include <iostream>
#include <vector>

using namespace std;

int minCandy(vector<int> &arr) {
    int n = arr.size();

    vector<int> leftcandy(n, 1);
    vector<int> rightcandy(n, 1);

    // left pass
    for (int i = 1; i < n; i++) {
        if (arr[i] > arr[i - 1])
            leftcandy[i] = leftcandy[i - 1] + 1;
    }

    // right pass
    for (int i = n - 2; i >= 0; i--){
        if (arr[i] > arr[i + 1])
            rightcandy[i] = rightcandy[i + 1] + 1;
    }

    // Calculate final answer
    int ans = 0;
    for (int i = 0; i < n; i++) {
        
        // Take max at each position
        ans += max(leftcandy[i], rightcandy[i]); 
    }

    return ans;
}

int main() {
    vector<int> arr = {1,2,3,4,5};

    cout << minCandy(arr);
}
Java