算法10-----分糖果

1、题目:

N个孩子在队伍中,每个孩子都有一定的等级值,相邻两个孩子等级高的拿到的糖果数量要比等级低的多,且每个孩子至少有一个糖果,所以最少队伍一共需多少糖果。

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?

如:输入:【5,4,1,1】,输出:7           【因为【3,2,1,1】和为7】

输入:[8,7,1,2,3,4,3,2,1,6,4,9],输出:26      【因为【3,2,1,2,3,4,2,1,2,1,2】和为26】

 

2、思路,

先创建一个全为1的长度为孩子数的列表list_value,从左往右遍历等级列表list_num,若右边等级比左边等级大,则右边值为左边值+1。再从右往左遍历等级列表,若左边等级比右边等级大且左边值比右边值小,则左边值等于右边值+1。

3、代码:

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

 

posted on 2018-04-28 14:10  吱吱了了  阅读(321)  评论(0编辑  收藏  举报

导航