✔ Easy to Understand Solution with Explanation
Problem: \nWe are given a vector of integer, ratings which contain ratings of \'n\' children standing in a line. We have to distribute candies to these children
## **Problem**: \nWe are given a vector of integer, ratings which contain ratings of \'n\' children standing in a line. We have to distribute candies to these children such that the total number of candies distributed are minimum. We have to consider the following conditions while distributing:\n* Each child must recieve atleast 1 candy.\n* The child with higher rating than his neighbours, must recieve more candies than them.\n\n## **Approach**:\nWe will take a vector of integer, candies, of size \'n\' and initialize all values with \'1\'. Then we would check whether the size of ratings, i.e., the number of children is less than or equal to 1, in which case, we would return the size itself.\n\nThen we will run a loop from 1 till n, where we will check if the rating of the current child is greater than the previous one, if yes, we would set the value of candies with the child as 1 more than the candies with the previous one.\n\nWe would then run a loop from n-1, i.e., the last child till i is greater than 0, and we would check if the previous, i.e., i-1 has more rating than i, then we would set value of i-1th one as, the maximum of increment of ith one and his own candies.\n\nFinally, we have assigned the candies to be distributed to each child, now we would just run an iteration for each child and add the number of candies to total number of candies.\n\nAnd we will return the total candies.\n\n## **Solution**:\n```\nclass Solution {\npublic:\n    int candy(vector<int>& ratings) {\n        int n = ratings.size(); //total number of children\n        int totalcandies = 0; //set total candies as 0\n        \n        if(n<=1) //check if the number of children are 1 or less\n            return n;\n        \n        vector<int> candies(n,1); // initialize a vector candies with 1 of size n\n        for(int i=1;i<n;i++)\n            if(ratings[i]>ratings[i-1]) //if the current child\'s rating is more than the previous one\n                candies[i]=candies[i-1]+1; //set his candies as 1 more than the previous one\n        \n        for(int i=n-1;i>0;i--)\n            if(ratings[i-1]>ratings[i]) //if the i-1th child has more rating than ith one\n                candies[i-1]=max(candies[i-1],candies[i]+1); //set the i-1th candies as maximum of his own and 1 more than the previous one\n        \n        for(int i=0;i<n;i++)\n            totalcandies+=candies[i]; //add each child\'s number of candies to the total\n        \n        return totalcandies; //return the total number of candies\n    }\n};\n```
['C']