[Leetcode] Candy @ Python

Source: Internet
Author: User

Original title address: https://oj.leetcode.com/problems/candy/

Test instructions

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?

Problem-solving ideas: Ask for the most stingy candy distribution number. First scan the array from front to back, if the sequence increments, + 1, and then scan the array from back to front, sequence increment, +1. Ensure that the lowest (ratings minimum) is always 1.

Code: Time Complexity O (n), spatial complexity O (n)

classSolution:#@param ratings, a list of integers    #@return An integer    defCandy (self, ratings): Candynum= [1] *Len (ratings) forIinchRange (1, Len (ratings)):ifRATINGS[I-1] <Ratings[i]: candynum[i]= Candynum[i-1] + 1 forIinchRange (len (ratings)-2,-1, 1):            ifRatings[i] > ratings[i + 1] andCandynum[i] <= Candynum[i + 1]: candynum[i]= Candynum[i + 1] + 1returnSUM (candynum)

[Leetcode] Candy @ Python

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.