You are viewing a single comment's thread. Return to all comments →
Here goes a working C++ solutions with two simple for loops to traverse forward and then reverse: https://www.hackerrank.com/challenges/candies/copy-from/24279388
Core Logic to get the count is as follows:
//start with one candy for each kid unsigned long long nTotalCandies = nTotalStudents; int nConsecutiveGreaterPos = 0; bool bTrendChanged = false; std::vector<int> Ranks(nTotalStudents,0); std::vector<int> Candies(nTotalStudents,0); //Forward Traversal std::cin>>Ranks[0]; for(int nKid = 1; nKid < nTotalStudents; ++nKid) { std::cin>>Ranks[nKid]; if((Ranks[nKid] > Ranks[nKid-1]) && (Candies[nKid] <= Candies[nKid-1])) { //update with new candies nTotalCandies += Candies[nKid-1]+1 - Candies[nKid]; Candies[nKid] = Candies[nKid-1]+1; } else if(!bTrendChanged && (Ranks[nKid] != Ranks[nKid-1]) { nConsecutiveGreaterPos = nKid-1; bTrendChanged = true; } } //Reverse traversal to update with latest candies for(int nKid = nTotalStudents-2; nKid >= nConsecutiveGreaterPos; --nKid) { if((Ranks[nKid] > Ranks[nKid+1]) && (Candies[nKid] <= Candies[nKid+1])) { //update with new candies nTotalCandies += Candies[nKid+1]+1 - Candies[nKid]; Candies[nKid] = Candies[nKid+1]+1; } }
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 →
Here goes a working C++ solutions with two simple for loops to traverse forward and then reverse: https://www.hackerrank.com/challenges/candies/copy-from/24279388
Core Logic to get the count is as follows: