[Leetcode]-candy points Candy problem

Source: Internet
Author: User

Candy

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.

Test Instructions Analysis:

In fact, as long as there is no bigger than him, you can only divide 1. If the left and right is bigger than him, then one more points around. The result is the most provincial.

The difficulty lies in: for example, [5,4,3,2,4] know that 5 is bigger than the two sides, but how to judge exactly how deep it is (where the trough is) "should be a few more appropriate." If you have been struggling to figure this out, then go to a "dead end".

In fact, the description of the topic itself is a good solution: the initialization of each person's candy number is initialized to 1. Each traversal considers only the left and right side, that is, to traverse from the left, if I>i-1 is candy[i]=candy[i-1], and then iterate from right to left, if I>i+1 and Candy[i]<=candy[i+1] Cand[i]=candy [I+1]+1; Such a two-time traversal, the left and right sides are taken into account. Finally add candy[i] and sum it up.


Code:

Class solution{public
:
    int Candy (vector<int> &ratings) {
      int n=ratings.size ();
      if (n==1) return 1;
      int i,sum=0;
      Vector<int> Candy (n,1);  First set the value of each person to 1

      //before scanning for
     (i=1;i<n;i++) {
        if (ratings[i]>ratings[i-1]) candy[i]=candy[i-1]+1;
     }

     Forward scan for
     (i=n-2;i>=0;i--) {
        if (ratings[i]>ratings[i+1] && candy[i]<=candy[i+1]) candy[i]=candy[i+1]+1;
     }

    for (i=0;i<n;i++)
        sum+=candy[i];
    
    return sum;
    }
};



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.