Candy

Greedy Algorithms Hard Hard

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:

1) There must be at least one candy for every child.

2) 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.

Examples:

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]

Constraints

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

Hints

  • Start by giving each child one candy to satisfy the first condition (at least one candy per child). Adjust the candy counts during the two passes to ensure the second condition is met.
  • After both passes, the candy count for each child will reflect the minimum candies needed to satisfy the conditions. Sum these values to get the total number of candies required.

Company Tags

Docker McKinsey & Company DoorDash Target Zoho Twilio Stripe Morgan Stanley Bloomberg GE Healthcare Ubisoft Uber Walmart Philips Healthcare ARM Salesforce Zomato Chewy Bain & Company Pinterest Medtronic Etsy NVIDIA Bungie Cloudflare Google Microsoft Amazon Meta Apple Netflix Adobe