这个DP解决方案有什么问题?

2024-10-03 21:31:46 发布

您现在位置:Python中文网/ 问答频道 /正文

这是一个骇客问题:爱丽丝是一名幼儿园老师。她想给班上的孩子们一些糖果。所有的孩子都排成一行(他们的位置是固定的),每个孩子都有一个根据他或她在班上的表现评分。爱丽丝想给每个孩子至少一块糖果。如果两个孩子挨着坐,那么评分较高的那个孩子必须得到更多的糖果。爱丽丝想省钱,所以她需要尽量减少给孩子们的糖果总数。你知道吗

n = int(input())
candies = 1
candy = 1
temp = int(input())
for i in range(1,n):
    temp1 = int(input())
    if (temp1>temp):
        candy = candy + 1        
    else:
        candy = 1

    temp = temp1
    candies = candies+candy 
    print candy

print candies 

测试阵列:n=10,n个元素[ 2 4 2 6 1 7 8 9 2 1]. 我得到的答案是18,而正确答案是19。我犯了一些我抓不住的错误。你知道吗

这是完成问题[https://www.hackerrank.com/challenges/candies]的链接


Tags: 答案input孩子老师评分tempint糖果
2条回答
    n = input()
    a = [input() for _ in xrange(n)]
   //min. candies he has to give  
    candies = [1] * n

        for i in xrange(1, n):
            if a[i] > a[i-1]:
                candies[i] = candies[i-1] + 1

        for i in xrange(n-2, -1, -1):
            if a[i] > a[i+1]:
                candies[i] = max(candies[i], candies[i+1] + 1)

        print sum(candies)

我就是这样做的,一开始就给每个孩子一块糖果。你知道吗

像这样修改代码。您只是从左方向迭代,但也应该检查右邻居。也从右边运行相同的循环,并取这两个值中的最大值。这应该是你的新任务。你知道吗

        n = int(input())
        candy = 1
        temp = int(input())
        list =[]
        rating =[]
        rating.append(temp)
        list.append(candy)
        for i in range(1,n):
            temp1 = int(input())
            rating.append(temp1)
            if (temp1>temp):
                candy = candy + 1        
            else:
                candy = 1
            list.append(candy)
            temp = temp1

        rating= rating[::-1]
        list = list[::-1]
        temp = rating[0]
        candies =list[0]
        for i in range(1,n):
            temp1 = rating[i]
            if (temp1>temp):
                list[i]= max(list[i-1]+1,list[i])

            candies =candies+list[i]
            temp = temp1

        print candies

相关问题 更多 >