oj--Distributing Candy

Source: Internet
Author: User

Topic Description

There are N (n<=100000) children standing in a row (numbered from 0 to n-1), each child has a rating value, stored in the ratings array. Teachers need to assign candy to them, each child needs at least one candy, for any adjacent two children I and i+1,rating value must be smaller than the rating value of the distribution of sweets more (rating the same not necessary to allocate as much candy).

Please calculate the minimum number of sweets required to complete the above allocation.

Topic Online Practice Address: http://www.itint5.com/oj/#31

The first idea of this question is to sort the ratings and store the order in the sort array, but the time complexity is too high because of first sorting and then updating.

So give up the sort, but the positive sequence traversal, to see whether the adjacent number is reversed, and then go through the reverse sequence, to see if the adjacent number is reversed. This completes the assignment in the time Complexity of O (n).

public class Candy {
	//returns the minimum number of sweets required public
		long Minimalcandies (int[] ratings) {
			int n = ratings.length;
			if (n = = 0) {return
				0;
			}
			Long sum = 0;
			Int[] count = new Int[n];
			for (int i = 0; i < n; i++) {
				count[i] = 1;
				
			}
			
			for (int i = 0; i < n-1 i++) {				
				if (ratings[i]>ratings[i+1]) {
					if (count[i]<=count[i+1)) {
						Count[i] = count[i+1]+1;	
					}	
				} else if (ratings[i]<ratings[i+1]) {
					if (count[i]>=count[i+1]) {
						count[i+1] = count[i]+1;	
					}
				}
			} for
			(int i = n-1 i > 0; i--) {
				if (ratings[i]>ratings[i-1)) {
					if (count[i]<=count[i-1)) {
						count[i]= count[i-1]+1	
					}
				} else if (Ratings[i]<ratings[i-1]) {
					if (Count[i]>=count[i-1]) {
						count[i-1]=count[i]+1		
					}
			}} for
			(int i = 0; i < n; i++) {
				sum = sum+ count[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.