<span style="font-family: Arial, Helvetica, sans-serif;">每日一刷,强迫学习</span>
There are N children standing in a line. Each child is assigned a rating value.
You are giving candies to these children subjected to the following requirements:
- Each child must have at least one candy.
- Children with a higher rating get more candies than their neighbors.
What is the minimum candies you must give?
要求:每人至少一颗;高等级的比相邻的糖果多。
注意:同一等级的没有要求。
思路:第一步,每个小朋友发一颗糖果;
第二步,从左向右扫,遇见当前等级比前一个等级高,则当前糖果=前一个糖果+1;
第三步,从右向左扫,遇见当前等级比后一个高,但是糖果数比后一个低,则当前=后一个+1;
代码:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package children;
/**
*
* @author zhaoyufeng
*/
public class Children {
public int candy(int[] ratings) {
int length = ratings.length;
int candySum = 0;
int[] candyEach = new int[length];
for (int i = 0; i < length; i++) {
candyEach[i] = 1;
}
for (int i = 1; i < length; i++) {
if (ratings[i] > ratings[i - 1]) {
candyEach[i] = candyEach[i - 1] + 1;
}
}
for (int i = length - 2; i >= 0; i--) {
if (ratings[i] > ratings[i + 1] && candyEach[i] <= candyEach[i + 1] ) {
candyEach[i] = candyEach[i + 1] + 1;
}
}
for (int i = 0; i <= length - 1; i++) {
System.out.print(" ratings[" + i + "]=" + ratings[i]);
}
System.out.println();
for (int i = 0; i <= length - 1; i++) {
System.out.print(" candyEach[" + i + "]=" + candyEach[i]);
candySum += candyEach[i];
}
System.out.println();
System.out.println(candySum);
return candySum;
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
// int a[] = {1, 2, 2, 4, 2, 1, 45, 3, 23, 2};
int a[] = {1,2,2};
Children child = new Children();
child.candy(a);
}
}