Candy

Pattern: Candy and assign cookies

hard

Give everyone one candy. Left to right, a child rated higher than the left neighbour gets one more than that neighbour. Right to left, a child rated higher than the right neighbour gets at least one more than that neighbour, keeping the larger of the two counts. Sum them.

The problem

Children stand in a line with ratings. Each child gets at least one candy, and a child with a higher rating than a neighbour gets more candies than that neighbour. Return the fewest candies in total. [1, 0, 2] gives 5; [1, 2, 2] gives 4.

Think first

  • What does each child need with respect to the left neighbour alone?
  • And the right neighbour alone?
  • How do you satisfy both?

Hints

    Brute force, and why it fails

    Repeatedly fix any child who breaks the rule until nothing changes: O(n²).

    The key insight

    The left rule and the right rule can each be met by one sweep, and taking the maximum keeps both, with no extra candy anywhere.

    Dry run

    10 
    11 
    12 

    ratings = [1, 0, 2]. Start with 1 each.

    Step 1 of 4

    The plan

    c = [1] * n
    for i in 1..n-1: if r[i] > r[i - 1]: c[i] = c[i - 1] + 1
    for i in n-2 down to 0: if r[i] > r[i + 1]: c[i] = max(c[i], c[i + 1] + 1)
    return sum(c)
    

    Complexity

    Time
    O(n)
    Space
    O(n)

    Two passes.

    Edge cases

    • Equal neighbours need nothing extra.
    • Strictly increasing: 1 + 2 + … + n.
    • One child: 1.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public int candy(int[] ratings) {
            int n = ratings.length;
            int[] c = new int[n];
            Arrays.fill(c, 1);                      // everyone gets at least one
            for (int i = 1; i < n; i++)             // left neighbours: a higher rating than the left gets more
                if (ratings[i] > ratings[i - 1]) c[i] = c[i - 1] + 1;
            for (int i = n - 2; i >= 0; i--)        // right neighbours, without breaking the left rule
                if (ratings[i] > ratings[i + 1]) c[i] = Math.max(c[i], c[i + 1] + 1);
            int total = 0;
            for (int x : c) total += x;
            return total;
        }
    }

    C++

    class Solution {
    public:
        int candy(vector<int>& ratings) {
            int n = static_cast<int>(ratings.size());
            vector<int> c(n, 1);                    // everyone gets at least one
            for (int i = 1; i < n; i++)             // left neighbours: a higher rating than the left gets more
                if (ratings[i] > ratings[i - 1]) c[i] = c[i - 1] + 1;
            for (int i = n - 2; i >= 0; i--)        // right neighbours, without breaking the left rule
                if (ratings[i] > ratings[i + 1]) c[i] = max(c[i], c[i + 1] + 1);
            int total = 0;
            for (int x : c) total += x;
            return total;
        }
    };

    Python

    class Solution:
        def candy(self, ratings: list[int]) -> int:
            n = len(ratings)
            c = [1] * n                             # everyone gets at least one
            for i in range(1, n):                   # left neighbours: a higher rating than the left gets more
                if ratings[i] > ratings[i - 1]:
                    c[i] = c[i - 1] + 1
            for i in range(n - 2, -1, -1):          # right neighbours, without breaking the left rule
                if ratings[i] > ratings[i + 1]:
                    c[i] = max(c[i], c[i + 1] + 1)
            return sum(c)

    Common mistakes

    • Overwriting in the second pass without max, which breaks the left rule.
    • Giving equal ratings more candies.

    Similar problems