title | description | authors | tags | categories | date | lastmod | draft | archive | ||||
---|---|---|---|---|---|---|---|---|---|---|---|---|
Candy |
Some description ... |
|
|
|
2020-03-09 00:42:43 -0700 |
2020-03-09 00:42:43 -0700 |
false |
false |
There are N
children standing in a line. Each child is assigned a rating value.
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.
- What is the minimum candies you must give?
Input: [1,0,2]
Output: 5
Explanation: You can allocate to the first, second and third child with 2, 1, 2 candies respectively.
Input: [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.
Time: O(N)
Space: O(N)
class Solution:
def candy(self, ratings: List[int]) -> int:
if not ratings or len(ratings)==0:
return 0
total = 0
leftToRight = [1] * len(ratings)
rightToLeft = [1] * len(ratings)
for i in range(1, len(ratings)):
if ratings[i] > ratings[i-1]:
leftToRight[i] = leftToRight[i-1]+1
for i in range(len(ratings)-2, -1, -1):
if ratings[i] > ratings[i+1]:
rightToLeft[i] = rightToLeft[i+1]+1
for i in range(len(ratings)):
total += max(leftToRight[i], rightToLeft[i])
return total