C + + Implementation--Child candy problem

Source: Internet
Author: User

#include <iostream> #include <vector> #include <algorithm> using namespace std; Question of candy/* There are N children standing in a line.

Each child is assigned a rating value. You are are giving candies to this children subjected to the following Requirements:each child must have at least one candy
.
Children with a higher rating to more candies than their.
* * Problem-solving ideas: traverse both sides, first of all a piece of sugar, the first time from left to right, if the current point than the former one more than a point. This ensures that the requirements are met in one direction.

The second time from right to left, if about two points, left above the right, but the left of the number of sweets not more than the right, then the left candy number equals the right candy number +1, which ensures that the other direction to meet the requirements.
Finally, add up the number of sweets in each position.
    * * int Candycount (vector<int>&rating) {int res = 0;

    Total children int n = rating.size ();
    Candy Set vector<int> Candy (n, 1);
    Iterate from left to right for (int i = 0;i < n-1;i++) {if (rating[i + 1] > Rating[i]) candy[i + 1] = Candy[i] + 1; //From right to left for (int i = n-1;i > 0;i--) {if (rating[i-1] > Rating[i] && candy[i-1] <
    = Candy[i]) candy[i-1] = Candy[i] + 1;

    }Cumulative result for (auto A:candy) {res + A;
return res;
    ///test function int main () {vector<int> rating{1,3,2,1,4,5,2};
    cout << Candycount (rating) << Endl;
return 0;
 }

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.