ExamAdda Logo

Candy

Easy

There are n children standing in a line. Each child is assigned a rating value given in the integer array ratings.

You are giving candies to these children subject to the following requirements:

• Each child must receive at least one candy.
• Children with a higher rating than an adjacent child must receive more candies than that child.

Return the minimum number of candies you need to distribute to satisfy these requirements.

Example 1

Input

3
1 0 2

Output

5

Explanation

One optimal distribution is:

2 1 2

The total number of candies distributed is 2 + 1 + 2 = 5.

Example 2

Input

3
1 2 2

Output

4

Explanation

One optimal distribution is:

1 2 1

The child with rating 2 receives more candies than the left neighbor, while the right child has the same rating and only needs one candy.

The minimum total is 4.

Constraints

1 ≤ ratings.length ≤ 2 × 10⁴
0 ≤ ratings[i] ≤ 2 × 10⁴

Hints:

Hint 1

Initially, give one candy to every child. Then scan from left to right to satisfy the left neighbor condition.

Hint 2

Perform another scan from right to left to satisfy the right neighbor condition. The answer is the sum of the maximum candies assigned at each position.

Author & Technical Reviewer

ExamAdda Technical Review Team

Technically reviewed by: ExamAdda Technical Review Team

Technical Reviewers, ExamAdda

Software engineers at ExamAdda who check every article's definitions, complexity claims and code examples before and after publishing.

Published

Aug 4, 2026

Last updated

Aug 4, 2026

Content Verification Methodology

Definitions and complexity claims were checked against authoritative computer-science references. Code examples were compiled and tested with standard, boundary and edge-case inputs.

Report a correction:editorial@examadda.org
Auto
Loading editor...
Input

Expected Output