This is a C++ Program that Solves Alice Kindergarden Candies Problem using Dynamic Programming method.
Alice is a kindergarden 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.
In this problem, every child should be given atleast one candy. For two adjacent children, one with the higher rating should be given more candies.
number of children, n=3 ratings of children, r=1, 2, 2 Minimum number of candies alice must buy=4
Here is source code of the C++ Program to solve Alice Kindergarden Candies Problem. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.
using namespace std;
int findSolution(vector<int> &ratings)
int size = ratings.size();
leftToRight = 1;
leftToRight[i] = leftToRight[i-1]+1;
leftToRight[i] = 1;
rightToLeft[size-1] = 1;
rightToLeft[i] = rightToLeft[i+1]+1;
rightToLeft[i] = 1;
cout<<"Enter the number of children ";
cout<<"Enter the rating of each child"<<endl;
cout<<"The Minimum number of candies Alice must buy is "<<endl;
In the main function, we take input for number of children and ratings of each child. These values are passed as arguments to the function findSolution. The final solution is returned by this function and displayed on the standard output.
Case-1: <pre lang="text" cssfile="hk1_style"> $ g++ alice.cpp $ ./a.out Enter the number of children 3 Enter the rating of each child 1 2 2 The Minimum number of candies Alice must buy is 4
Sanfoundry Global Education & Learning Series – Dynamic Programming Problems.
To practice all Dynamic Programming Problems, here is complete set of 100+ Problems and Solutions.