简体   繁体   中英

what is wrong with this DP solution?

It's a hackerrank question: Alice is a kindergarten teacher. She wants to give some candies to the children in her class. All the children sit in a line ( their positions are fixed), and each of them has a rating score according to his or her performance in the class. Alice wants to give at least 1 candy to each child. If two children sit next to each other, then the one with the higher rating must get more candies. Alice wants to save money, so she needs to minimize the total number of candies given to the children.

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 

Test array : n = 10, n elements are [ 2 4 2 6 1 7 8 9 2 1]. I am getting 18 as the answer while 19 is the correct answer. I am doing some mistake which I am unable to catch.

This is the link to complete question [ https://www.hackerrank.com/challenges/candies ]

Modify your code like this. You are only iterating from the left direction but the right neighbour should also be checked. Run the same loop from right also and take the maximum of those two values. This should be your new candy assignment.

        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
    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)

That is how i did this, by giving one candy at starting to each child.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM