Algo-Sim › Greedy

Candy

Hard · Greedy · step through it in Java, Python and C++ on your own input

Children in a row get candy; a higher rating than a neighbour means more candy. Two greedy passes, then the max at each child.

Problem

There are n children in a line, each with a rating ratings[i]. Every child gets at least one candy, and a child with a higher rating than an adjacent child gets more candies than that neighbour. Return the minimum number of candies needed.

Constraints

Edge cases to test

Follow-up questions

Why two passes?
The left pass satisfies every left neighbour, the right pass every right one, and taking the max keeps both: O(n) time, O(n) space.
Can it be done in O(1) space?
Count lengths of rising and falling slopes and add arithmetic series, adjusting the peak: O(n) time, O(1) space.

Solution

Java

public int candy(int[] ratings) {
    int n = ratings.length;
    int[] candies = new int[n];
    Arrays.fill(candies, 1);
    for (int i = 1; i < n; i++)
        if (ratings[i] > ratings[i - 1]) candies[i] = candies[i - 1] + 1;
    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 total = 0;
    for (int c : candies) total += c;
    return total;
}

Python

def candy(ratings):
    n = len(ratings)
    candies = [1] * n
    for i in range(1, n):
        if ratings[i] > ratings[i - 1]:
            candies[i] = candies[i - 1] + 1
    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)

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    int candy(vector<int> &ratings) {
        int n = int(ratings.size());
        vector<int> candies(n, 1);
        for (int i = 1; i < n; i++)
            if (ratings[i] > ratings[i - 1]) candies[i] = candies[i - 1] + 1;
        for (int i = n - 2; i >= 0; i--)
            if (ratings[i] > ratings[i + 1]) candies[i] = max(candies[i], candies[i + 1] + 1);
        int total = 0;
        for (int c : candies) total += c;
        return total;
    }
};

More Greedy problems