[Leet Code 135]candy

Source: Internet
Author: User

1 topics

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?

2 Ideas

According to the line of thought, each child has at least one candy, first from left to right to go through, write up the number of increased candy, and then walk from right to left to complete the decreasing number of sweets. This approach can be used for problems related to the size and left and right side data. In addition, there is another space complexity O (1), Time complexity O (n) ideas, can refer to http://www.cnblogs.com/felixfang/p/3620086.html.

3 Code

  Public intCandyint[] ratings) {          if(Ratings = =NULL|| Ratings.length = = 0)          {              return0; }          int[] Candynums =New int[Ratings.length]; candynums[0] = 1;  for(inti = 1; i < ratings.length; i++)          {              if(Ratings[i] > Ratings[i-1])//If the first child is taller than the I-1 child, {candynums[i]= Candynums[i-1]+1; }              else//Everyone has at least one candy{Candynums[i]= 1; }          }                    for(inti = ratings.length-2; I >= 0; i--)          {                          if(Ratings[i] > ratings[i + 1] && candynums[i] <= candynums[i + 1])//If the first child is taller than the i + 1 child and the candy is less than i+1 sweets {candynums[i]= Candynums[i + 1] + 1; }            }                  intTotal = 0;  for(inti = 0; i < candynums.length; i++) { Total+=Candynums[i]; }                returnTotal ; }

[Leet Code 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.