Leetcode 135. Distribute candy greedy algorithm

The teacher wants to distribute candies to the children. N children stand in a straight line, and the teacher will rate each child in advance based on their performance.

You need to help the teacher distribute candies to these children according to the following requirements:

Each child is allocated at least 1 candy.
Among the adjacent children, the child with the higher score must get more candy.
So how many candies should the teacher prepare?

example 1:

Input: [1,0,2]
Output: 5
Explanation: You can distribute 2, 1, and 2 candies to the three children.

example2:
Input: [1,2,2]
Output: 4
Explanation: You can distribute 1, 2, and 1 candy to the three children.
The third child only gets 1 candy, which already meets the above two conditions.

This problem can be solved by a greedy algorithm
(I want to use a dictionary to solve this problem, but the dictionary does not seem to have an index)
first create a sequence of ratings length, and ensure that each child has 1 candy.
Traverse and filter from left to right.
After
selecting the children with higher scores on the right than the ones on the left, add one to the number of children with higher scores than those with lower scores. Then traverse from right to left to filter out
the children with higher scores on the left and then let the children with higher scores than the children with lower scores. The number of candies is increased by one
. After two traversals,
all the children with higher scores than the children next to them get more second candies than the children with lower scores around them.
Finally, the value in ans is traversed and added to res to
output ans. Up

It uses a lot of recycling, and the operating efficiency is not particularly ideal

class Solution:
    def candy(self, ratings: List[int]) -> int:
        res = 0
        ans = [1] * len(ratings)
        
        for i in range(1, len(ratings)):
            if ratings[i] > ratings[i - 1] and ans[i] <= ans[i - 1]:
                ans[i] = ans[i - 1] + 1
        
        for j in range (len(ratings) -2, -1 , -1):
            if ratings[j] > ratings[j + 1] and ans[j] <= ans[j + 1]:
                ans[j] = ans[j + 1] + 1
        
        for z in ans:
            res += z
        
        return res

Guess you like

Origin blog.csdn.net/weixin_50791900/article/details/111637774