Candy

Hard Top 250
Associated Patterns
Interviewed At (Company Tags)
GoogleAmazonMicrosoftApple

Problem Description

There are n children standing in a line. Each child is assigned a rating value given in the integer array ratings.

You are giving candies to these children subjected to the following requirements:

  • Each child must have at least one candy.
  • Children with a higher rating get more candies than their neighbors.

Return the minimum number of candies you need to have to distribute the candies.


Examples

Example 1:

Input: ratings = [1,0,2] Output: 5 Explanation: You can allocate to the first, second and third child with 2, 1, 2 candies respectively.

Example 2:

Input: ratings = [1,2,2] Output: 4 Explanation: You can allocate to the first, second and third child with 1, 2, 1 candies respectively. The third child gets 1 candy because it satisfies the above two conditions.


Constraints

  • n == ratings.length
  • 1 ≤ n ≤ 2 * 10⁴
  • 0 ≤ ratings[i] ≤ 2 * 10⁴

Two-Pass Greedy Logic

A child has two neighbors: one on the left, one on the right. Satisfying both constraints simultaneously in a single pass is tricky.

Instead, we split the constraints into two separate linear passes:

  1. Left-to-Right Pass (Satisfy Left Neighbors):
    • Initialize candies array with 1 for each child.
    • For i from 1 to n - 1: if ratings[i] > ratings[i - 1], then candies[i] = candies[i - 1] + 1.
  2. Right-to-Left Pass (Satisfy Right Neighbors):
    • For i from n - 2 down to 0: if ratings[i] > ratings[i + 1], then candies[i] must be updated to be at least candies[i + 1] + 1. Specifically: candies[i] = max(candies[i], candies[i + 1] + 1).

Summing the elements of candies at the end gives the optimal minimum candy count.


Solution: Two-Pass Greedy

import java.util.*;

class Solution {
    public int candy(int[] ratings) {
        int n = ratings.length;
        int[] candies = new int[n];
        Arrays.fill(candies, 1);

        // Left-to-right pass
        for (int i = 1; i < n; i++) {
            if (ratings[i] > ratings[i - 1]) {
                candies[i] = candies[i - 1] + 1;
            }
        }

        // Right-to-left pass
        for (int i = n - 2; i >= 0; i--) {
            if (ratings[i] > ratings[i + 1]) {
                candies[i] = Math.max(candies[i], candies[i + 1] + 1);
            }
        }

        int totalCandies = 0;
        for (int c : candies) {
            totalCandies += c;
        }

        return totalCandies;
    }
}
class Solution:
    def candy(self, ratings: list[int]) -> int:
        n = len(ratings)
        candies = [1] * n

        # Left-to-right pass
        for i in range(1, n):
            if ratings[i] > ratings[i - 1]:
                candies[i] = candies[i - 1] + 1

        # Right-to-left pass
        for i in range(n - 2, -1, -1):
            if ratings[i] > ratings[i + 1]:
                candies[i] = max(candies[i], candies[i + 1] + 1)

        return sum(candies)
#include <vector>
#include <numeric>
#include <algorithm>

class Solution {
public:
    int candy(std::vector<int>& ratings) {
        int n = ratings.size();
        std::vector<int> candies(n, 1);

        // Left-to-right pass
        for (int i = 1; i < n; i++) {
            if (ratings[i] > ratings[i - 1]) {
                candies[i] = candies[i - 1] + 1;
            }
        }

        // Right-to-left pass
        for (int i = n - 2; i >= 0; i--) {
            if (ratings[i] > ratings[i + 1]) {
                candies[i] = std::max(candies[i], candies[i + 1] + 1);
            }
        }

        return std::accumulate(candies.begin(), candies.end(), 0);
    }
};

Complexity Analysis:

  • Time Complexity: O(N) where N is the length of ratings. We make two passes over the array.
  • Space Complexity: O(N) to store the candy count for each child.

← All Problems