2.135-分发糖果
1 def candy(ratings): 2 result=[1 for i in range(len(ratings))] 3 for i in range(len(ratings)-1): 4 if ratings[i]>ratings[i+1] and result[i]<=result[i+1]: 5 result[i]+=result[i+1]-result[i]+1 6 if ratings[i]<ratings[i+1] and result[i]>=result[i+1]: 7 result[i+1]+=result[i]-result[i+1]+1 8 for j in range(len(ratings)-1,0,-1): 9 if ratings[j]>ratings[j-1] and result[j]<=result[j-1]: 10 result[j]+=result[j-1]-result[j]+1 11 if ratings[j]<ratings[j-1] and result[j]>=result[j-1]: 12 result[j-1] += result[j ] - result[j-1] + 1 13 print(result) 14 return sum(result)