Candy Distribution
Updated
Problem statement
There are n children standing in a line. The integer array ratings gives each child's rating.
Distribute candies subject to these rules:
- Every child receives at least one candy.
- A child with a higher rating than an adjacent child receives more candies than that neighbor.
Return the minimum total number of candies required.
Function
minimumCandies(ratings: int[]) → intExamples
Example 1
ratings = [1,0,2]return = 5The middle child has the lowest rating and gets one candy. Both end children rate higher than the middle one, so each needs more than one. The smallest valid split is [2,1,2], which adds up to five.
Example 2
ratings = [1,2,2]return = 4The second child rates higher than the first, so the second child needs more candies. The third child has the same rating as the second, so no rule links them. The smallest valid split is [1,2,1], a total of four. Equal ratings do not require equal candy counts.
Example 3
ratings = [1,3,4,5,2]return = 11Ratings rise across the first four children, so their candies must rise too. The last child rates lower than the fourth, so one candy is enough there. The smallest valid split is [1,2,3,4,1], a total of eleven.
Constraints
1 <= ratings.length <= 2 * 10^4.0 <= ratings[i] <= 2 * 10^4.
More Accenture interview questions
- Nearest Composite NumberOA · Seen Sep 2026
- Minimum Password IncrementsOA · Seen Sep 2026
- Reduce a Number to One DigitOA · Seen Sep 2026
- Customers Who Never OrderedOA · Seen Sep 2026
- Economical TripOA · Seen Sep 2026
- Coin ChangeOA · Seen Sep 2026
- Validate Email AddressOA · Seen Sep 2026
- Closest Rhyming WordOA · Seen Aug 2026
- Array Leader ElementsOA · Seen Nov 2025
- Alternating Index Square SumONSITE INTERVIEW · Seen Sep 2026
Similar questions at other companies
- Earn the Most 🐝Capital One · OACapital One interview questions
- Minimum Cost to Merge Values into OnePayPal · OAPayPal interview questions
- Minimum Operations to Sort with Rotations Then SwapsBank of New York Mellon · OA
- Minimum Cost of Left and Right PropagationAmazon · OA
- Minimum Rounds to Complete All TasksInfosys · OAInfosys interview questions
- Reschedule Meetings for Maximum Free TimeFivetran · OAFivetran interview questions
- Maximum Easy Tasks After RearrangingIBM · OAIBM interview questions
- Minimum Cost K-Capable ModelsMicrosoft · OAMicrosoft interview questions
- Maximum ScoreNVIDIA · OANVIDIA interview questions
- Maximum Distinct Values After Unit AdjustmentsBirla Pivot · OA