Algorithm 10 - Divide candy

1. Subject:

N children are in the team, each child has a certain level value, the number of candies obtained by two adjacent children with a higher level is more than that of a lower level, and each child has at least one candy, so the minimum team has a total of How much candy is needed.

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?

Such as: input: [5, 4, 1, 1], output: 7 [because the sum of [3, 2, 1, 1] is 7]

Input: [8,7,1,2,3,4,3,2,1,6,4,9], Output: 26 [Because [3, 2, 1, 2, 3, 4, 2, 1, 2, 1, 2] and 26]

 

2, ideas,

First create a list list_value whose length is the number of children, and traverse the level list list_num from left to right. If the right level is greater than the left level, the right value is the left value + 1. Then traverse the level list from right to left. If the left level is greater than the right level and the left value is smaller than the right value, the left value is equal to the right value + 1.

3. Code:

def candy(list_num):
    list_value=[1]*len(list_num)
    for i,j in enumerate(list_num):
        if i==len(list_num)-1:
            break
        if j<list_num[i+1]:
            list_value[i+1]=list_value[i]+1
    list_value.reverse()
    list_num.reverse()
    for i,j in enumerate(list_num):
        if i==len(list_num)-1:
            break
        if j<list_num[i+1] and list_value[i]>=list_value[i+1]:
            list_value[i+1]=list_value[i]+1
    sum=0
    for i in list_value:
        sum+=i
    return sum

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325017083&siteId=291194637