135. Candy ๐ฌ
Difficulty: Hard
- Tags: Greedy
, Array
Description
There are n
children standing in a row. Each child is assigned a rating value given in the ratings
integer array.
You are giving candy to the children under the following conditions:
Each child must have at least one piece of candy.
Children with higher ratings (larger rating values) will receive more candy than their neighbors with lower ratings.
Return the minimum amount of candy you need to distribute to children.
Examples
Example 1:
Input:
Output:
Explanation: You can allocate candies to the first, second, and third child as follows:
First child: 2 candies
Second child: 1 candy
Third child: 2 candies
Example 2:
Input:
Output:
Explanation: You can allocate candies to the first, second, and third child as follows:
First child: 1 candy
Second child: 2 candies
Third child: 1 candy
The third child gets 1 candy because it satisfies the conditions.
Solution ๐ก
We can solve this problem using a two-pass greedy approach:
First pass: Traverse from left to right. For each child, if the current child has a higher rating than the previous child, give more candy.
Second pass: Traverse from right to left. For each child, if the current child has a higher rating than the next child, adjust the candy count to satisfy the condition.
Java
Time Complexity โณ
The time complexity is O(n) because we are traversing the array twice (left-to-right and right-to-left), where
n
is the length of theratings
array.
Space Complexity ๐พ
The space complexity is O(n) because we are using an extra array to store the number of candies for each child.
You can find the full solution here.
Last updated