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 used DP. The right to left and left to right solution works. But it is a lot fun if you use DP.
Every student's candy value depends on their left and right student.
So build the solution by calculating the neighbours value and then reccursing back to the top using:
funcgetMaxFromRight(intidx)://Handle base case and edge cases hereifranking[idx-1]<ranking[idx]>ranking[idx+1];thencandy[idx]=max(candy[idx-1],getMaxFromRight(idx+1))+1;elseif(ranking[idx+1]<ranking[idx])thencandy[idx]=getMaxFromRight(idx+1)+1;elseif(ranking[idx-1]<ranking[idx])thencandy[idx]=candy[idx-1]+1;getMaxFromRight(idx+1)+1;elsecandy[idx]=1;getMaxFromRight(idx+1)+1;returncandy[idx]
Note: You have to handle base case for return and also edge cases of idx-1 >=0 and idx+1 < candy.length
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 used DP. The right to left and left to right solution works. But it is a lot fun if you use DP.
Note: You have to handle base case for return and also edge cases of idx-1 >=0 and idx+1 < candy.length