We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
I did not sove this problem with dynamic programming, I just looked at the cases and where they fail. You can start from the second student and give more candy to the next student who score more than the first and so on, but we don't get to know what peg to choose when the next student score less from 1 to previous student's candy. So. we do nothing and repeat the process doing the same approach from the end trying to find next incements. Here's the code.
defcandies(n,score):# give one candy to everybody woohoocandy=[1forxinrange(n)]# iterate from start,# give one more candy# if next preson's score# is more than previous person'sforiinrange(1,n,1):ifscore[i]>score[i-1]:candy[i]=candy[i-1]+1# iterate from the end,# give one more candy# if next preson's score# is more than previous person's# and candy is not more than previous person'sforiinrange(n-1,0,-1):ifscore[i-1]>score[i]andcandy[i-1]<=candy[i]:candy[i-1]=candy[i]+1# print(candy)total=sum(candy)returntotal
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Candies
You are viewing a single comment's thread. Return to all comments →
I did not sove this problem with dynamic programming, I just looked at the cases and where they fail. You can start from the second student and give more candy to the next student who score more than the first and so on, but we don't get to know what peg to choose when the next student score less from 1 to previous student's candy. So. we do nothing and repeat the process doing the same approach from the end trying to find next incements. Here's the code.