[Java] 135. Distribute candies-----find the rules! ! !

The teacher wants to distribute candies to the children. N children stand in a straight line, and the teacher will rate each child in advance based on their performance.

You need to help the teacher distribute candies to these children according to the following requirements:

Each child is allocated at least 1 candy.
Among the neighboring children, the child with a higher score must get more candies.
So, how many sweets does the teacher need to prepare at least?

Example 1:

Input: [1,0,2]
Output: 5
Explanation: You can distribute 2, 1, and 2 candies to the three children respectively.
Example 2:

Input: [1,2,2]
Output: 4
Explanation: You can distribute 1, 2, and 1 candy to the three children.
The third child only gets 1 candy, which already meets the above two conditions.

public static int candy(int[] ratings) {
    
    
		if(ratings.length==0) {
    
    
			return 0;
		}
		int[]a=new int[ratings.length];
		a[0]=1;
		//先正序遍历,如果后一位比前一位高分,就给比前一位多1的糖果,否则给1
		for(int i=1;i<ratings.length;i++) {
    
    
			if(ratings[i]>ratings[i-1]) {
    
    
				a[i]=a[i-1]+1;
			}else {
    
    
				a[i]=1;
			}
		}
		//在倒叙遍历,如果前一位比后一位高分并且得到的糖果小于或等于后一位,就给前一位孩子比后一位孩子多一个糖果
		for(int i=ratings.length-2;i>=0;i--) {
    
    
			if(ratings[i]>ratings[i+1]&&a[i]<=a[i+1]) {
    
    
				a[i]=a[i+1]+1;
			}
		}
		int sum=0;
		for (int i : a) {
    
    
			sum+=i;
		} 
		return sum;
	}

Guess you like

Origin blog.csdn.net/qq_44461217/article/details/111631030