Stay button --135: distributing candy

135: Distribute candy (hard)

The teacher wanted to distribute candy to children, there are N children stood in a straight line, the teacher will be based on each child's performance in advance to give them score.
You need to follow these requirements to help teachers distribute candy to the children:
each child assigned to at least one candy.
Adjacent to the child, the child must get a high score more candy.
So this down, how many pieces of candy teachers need to be prepared at least it?

Example 1:
Input: [1,0,2]
Output: 5
Explanation: You can give these children three pieces of candy to distribute 2,1,2 respectively.
Example 2:
Input: [1,2,2]
Output: 4
Explanation: You can give these children three pieces of candy to distribute 1,2,1 respectively.
The third child only get a candy, the above two conditions which have been met.
Source: stay button (LeetCode)

Thinking

Just started to try to see if I can direct violence to solve, once traversed
it will meet three conditions
1: ratings [i - 1] == ratings [i]

2:ratings[i - 1] < ratings[i]

3: ratings [i - 1] > ratings [i]
increment after a good solution is a former number +1 child, like, decreasing, then it is a child's first number-1, but if sustained descending several times, leading to <1, then do not meet the meaning of the questions. This time is not going back. I think this idea is not easy to achieve.
I wanted either to traverse it twice.
Forward traversal, to ensure that each child is left if the score is lower than his, he will certainly be less than the number of candy.
Reverse traversal, to ensure that every child the right side if the score is lower than his, he will certainly be less than the number of candy.

Code

public  int candy(int[] ratings) {
    	int len = ratings.length;
    	if(len == 0) return 0;
		int[] candy_num = new int[len];
		int sum =0;
		candy_num[0] = 1;
    	for(int i =1 ;i<len;i++) {
    		if(ratings[i]>ratings[i-1]) {
    			candy_num[i] =candy_num[i-1]+1;
    		}
    		else candy_num[i] = 1;
    	}
    	for(int i =len-1 ;i>0;i--) {
            //判断语句易少条件
    		if(ratings[i]<ratings[i-1]&&candy_num[i-1] <=candy_num[i]) {
    			candy_num[i-1] =candy_num[i]+1;
            }    		
    	}
    	for(int i =0 ;i<len;i++) {
    		sum+= candy_num[i];
    	}
    	return sum;
    }	
	
Published 21 original articles · won praise 1 · views 2402

Guess you like

Origin blog.csdn.net/Better_WZQ/article/details/104541153