Java for Leetcode 135 Candy

Source: Internet
Author: User

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:

Two-way climbing problem, from the past, back and forth from the previous sweep again, Java implementation is as follows:

public int candy (int[] ratings) {int sum = 0;int[] Candies = new Int[ratings.length];for (int i = 0; i < ratings.length -1; i++) if (Ratings[i] < Ratings[i + 1]) Candies[i + 1] = Candies[i] + 1;for (int i = ratings.length-2; I >= 0; i--) if (Ratings[i + 1] < Ratings[i]) candies[i] = Math.max (Candies[i], candies[i + 1] + 1); for (int i = 0; i < Candies.lengt H i++) Sum + = 1 + candies[i];return sum;}

Java for 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.