Candy

Asked atMicrosoft
1Give yourself 5 minutes
2Answer out loud, not in your head
3Then compare with the answer below

The problem

A line of N kids is standing there. The rating values listed in the integer array ratings are assigned to each kid.

These kids are receiving candy, according to the following criteria:

  • There must be at least one candy for every child.

  • Kids whose scores are higher than their neighbours receive more candies than their neighbours.

Return the minimum number of candies needed to distribute among children.

Input : ratings = [1, 0, 5]

Output : 5

Explanation : The distribution of candies will be 2 , 1 , 2 to first , second , third child respectively.

Input : ratings = [1, 2, 2]

Output : 4

Explanation : The distribution of candies will be 1 , 2 , 1 to first , second , third child respectively. The third gets only 1 candy because it satisfy above two criteria.

Input : ratings = [1, 2, 1, 4, 5]

  • 1 <= n <= 104
  • 0 <= ratings[i] <= 105

cpp

class Solution {
public:
    int candy(vector<int>& ratings) {
        //your code goes here
    }
};

java

class Solution {
    public int candy(int[] ratings) {
       //your code goes here
    }
}

python

class Solution:
    def candy(self, ratings):
        #your code goes here

javascript

class Solution {
    candy(ratings) {
        //your code goes here
    }
}

csharp

public class Solution {
    public int Candy(int[] ratings) {

    }
}

go

func candy(ratings []int) int {

}
Stuck? Show a way to structure it+
  1. 01Initialize all candies to one
  2. 02Satisfy rising slopes from the left
  3. 03Satisfy descending slopes from the right with max
  4. 04Sum after both constraints are met

Reference answer

Then expect these follow-ups

  • Can this be solved in O(1) extra space?

    Tests: complexity analysis

  • Why does taking max satisfy both neighbors?

    Tests: correctness reasoning

Hiring now

Software engineer roles are open right now

landed applies to roles like these for you, on each company’s own site, with answers written for the role.

Get 5x interviews10 free auto-applies. No card.
  • Senior Software Engineer -.NET

    Tyler Technologies · Annapolis, Maryland

  • Software Development Engineer II

    SaaS Labs · Bengaluru, Karnataka, India

  • Advanced Software Engineer - Product Architect (Legal, Safety, and Risk)

    Metropolitan Transportation Authority · New York, NY

Or practice this question first

Next question