FastPrepMinimum Candies by Rating
Problems/Minimum Candies by Rating

Minimum Candies by Rating

Groww logoGroww● HardINTERNONSITE INTERVIEW
QuestionFunctionExamplesConstraints

Problem statement

Source note: An interview report names the rating-based candy distribution task. This practice contract gives every child at least one candy and requires a higher-rated adjacent child to receive more candy.

There are n children standing in a line. The integer array ratings gives each child's rating.

Give candies to the children subject to these rules:

  • Every child receives at least one candy.
  • If a child has a higher rating than an adjacent child, the higher-rated child must receive more candies.

Return the minimum total number of candies required.

Function

minimumCandies(ratings: int[]) → long

Examples

Example 1

ratings = [1,0,2]return = 5

The minimum valid allocation is [2,1,2], whose total is 5.

Example 2

ratings = [1,2,2]return = 4

The allocation [1,2,1] is valid. Equal ratings do not require different candy counts.

Constraints

  • 1 <= ratings.length <= 200000
  • -10^9 <= ratings[i] <= 10^9
  • The answer fits in a signed 64-bit integer.

More Groww problems

  • Maximum Sum Desirable SubarrayPHONE SCREEN · Seen Oct 2026
  • Sliding Window MaximumPHONE SCREEN · Seen Sep 2026
  • Best Time to Buy and Sell Stock IIONSITE INTERVIEW · Seen Sep 2026
See Groww hiring insights
Saved
class Solution {
    public long minimumCandies(int[] ratings) {
        // write your code here
    }
}
Checking account…