Leetcode | | 135, Candy

Source: Internet
Author: User

Problem:

There is N children standing in a line. Each child is assigned a rating value.

You is giving candies to these children subjected to the following requirements:

    • Each child must has at least one candy.
    • Children with a higher rating get more candies than their neighbors.

What's the minimum candies you must give?

Hide TagsGreedyTest instructions: Give sweets to small pots, high-quality candy to more

Thinking:

(1) A simple greedy question, why is the pass rate so low?? There is no mention in the title how to make candy when the property is equal. is not a serious problem again. Submit Discovery,

122 of the small pot friends sent 4 candies, the third small pot friends sent 1 sweets, in exchange for you are small pot friends, you will be happy ...

(2) Apart from the same situation, the problem should be handled as long as it is in the descending condition. Increment or disorderly order to deal with something.

Code

Class solution{Public:int Candy (vector<int> &ratings) {int total = 0;  Total Candies int length = 0; Continuous descending length of rate int nprecancnt = 1;    Previous Child ' s candy count int beforedenc = nprecancnt;        if (ratings.begin () = Ratings.end ()) {total++;//counting the first child ' s candy (1).            for (Vector<int>::iterator i = Ratings.begin () +1; i!= ratings.end (); i++) {if (*i < * (i-1))                {length++;                if (beforedenc <= length) {total++;                } Total + = length;    nprecancnt = 1;            This are important, it ensures that once we leave the decending sequence, candy number start from 1}                else {int curcancnt = 0;                if (*i > * (i-1)) {curcancnt = (nprecancnt + 1);        }        else {curcancnt = 1;                } Total + = curcancnt;                nprecancnt = curcancnt;    length = 0;            Reset length of decending sequence beforedenc = curcancnt; }}}, return total;};


Leetcode | | 135, Candy

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.