Leetcode 135. distribute candy

Topic links:

Link: https: //leetcode-cn.com/problems/candy

 

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 the requirements of the teacher to help the children and hand out candy:

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:

Enter: [1,0,2]
Output: 5
Explanation: You can give these children three pieces of candy to distribute 2,1,2 respectively.
Example 2:

Enter: [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.

answer:

Traversed twice, first of all nums value of 1,

First from left to right, if the ratings [i]> ratings [i-1], then nums [i] = nums [i-1] +1

And then from right to left when, if nums [i-1]> nums [i], the comparator nums [i] +1 and nums [i-1], whichever is greater that

 1 int candy(int* ratings, int ratingsSize){
 2     int i,ans=0;
 3     int nums[ratingsSize];
 4     if(ratingsSize == 0)
 5         return 0;
 6     for(int i=0 ;i <ratingsSize;i++)
 7         nums[i] = 1;
 8     for(i = 1; i<ratingsSize ; i++ )
 9         if(ratings[i] > ratings[i - 1] )
10             nums[i] = nums[i - 1] + 1;
11 
12     //for(i = 0 ;i < ratingsSize; i++)
13         //printf("%d ",nums[i]);
14     //puts("");
15     for(i = ratingsSize - 1; i >= 1; i-- )
16         if(ratings[i - 1] > ratings[i] )
17             nums[i - 1] = max(nums[i] + 1,nums[i - 1]) ;
18 
19     //for(i = 0 ;i < ratingsSize; i++)
20       //  printf("%d ",nums[i]);
21 
22     //puts("");
23     for(i = 0 ;i < ratingsSize; i++)
24         ans += nums[i];
25 
26     return ans;
27 }
View Code

 

Guess you like

Origin www.cnblogs.com/tijie/p/12097176.html