Date and Time: Sep 13, 2024, 10:56 (EST)
Link: https://leetcode.com/problems/candy/
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 subjected to the following requirements:
-
Each child must have at least one candy.
-
Children with a higher rating get more candies than their neighbors.
Return the minimum number of candies you need to have to distribute the candies to the children.
Example 1:
Input: ratings = [1,0,2]
Output: 5
Explanation: You can allocate to the first, second and third child with 2, 1, 2 candies respectively.
Example 2:
Input: ratings = [1,2,2]
Output: 4
Explanation: You can allocate to the first, second and third child with 1, 2, 1 candies respectively.
The third child gets 1 candy because it satisfies the above two conditions.
-
n == ratings.length -
1 <= n <= 2 * 10^4 -
0 <= ratings[i] <= 2 * 10^4
-
We are given two requirements, to satisfy the first requirement, we can first initialize an array
candy = [1] * len(ratings). -
Since the children with a higher rating get more candies than their neighbors, we can first loop over
ratingsfrom left to right ane detect if an element inratingsis greater than its left neighbor, if so, we update thecandy[i] = candy[i-1]+1, because we want to have higher value than its neighbor. -
We do the same thing from the right to the left and check if an element is greater than its right neighbor. If so, we want to update
candy[i] = max(candy[i], candy[i+1]+1), we don't want to replacecandy[i]with a value lower than its originalcandy[i]. -
Finally, we just return the sum of
candy[].
class Solution:
def candy(self, ratings: List[int]) -> int:
# Initialize all children with 1 candy
# Compare from left to right: if ratings[i] > ratings[i-1], update candy[i] = candy[i-1]+1
# From right to left: if ratings[i] > ratings[i+1]: maintain candy[i] = max(candy[i], candy[i+1]+1)
# TC: O(n), n=len(ratings), SC: O(n)
candy = [1] * len(ratings)
# Compare from l to r
for i in range(1, len(ratings)):
if ratings[i] > ratings[i-1]:
candy[i] = candy[i-1] + 1
# Compare from r to l
for i in range(len(ratings)-2, -1, -1):
if ratings[i] > ratings[i+1]:
candy[i] = max(candy[i], candy[i+1] + 1)
return sum(candy)Time Complexity: n is the length of ratings.
Space Complexity: