Distribute Candy

There are N children standing in a line. Each child is assigned a rating value.

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.

What is the minimum candies you must give?

Sample Input :

Ratings : [1 2]

Sample Output :

3

The candidate with 1 rating gets 1 candy and candidate with rating cannot get 1 candy as 1 is its neighbor. So rating 2 candidate gets 2 candies. In total, 2+1 = 3 candies need to be given out.

Interview Code Editor
Hints
  • Solution Approach
  • Complete Solution
2555 successful submissions.
Asked In:
  • Microsoft
Click here to jump start your coding interview preparation