题 目
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、每个孩子至少分到一颗糖果;
2、如果一个孩子的分数比旁边的孩子分数高,则他的糖果一定要比旁边的孩子数量多;
求问,一共要多少个糖果?
思路
1、每个孩子首先先分到一颗糖果;
2、然后从左到右,如果如果右边孩子比左边孩子分数高的,就让右边孩子的糖果分配数量=左边孩子糖果数+1;
3、从右到左再次遍历一遍,如果左边孩子比右边孩子分数高,且左边孩子的糖果<=右边孩子的糖果,则将左边孩子的糖果数量=右边孩子糖果数量+1;
这里为什么要判断试一下是不是糖果数量<=,因为第一轮可能会有一些本身权重就比左边低的,这时候糖果数量已经满足条件了,再+1反而影响了最小糖果数量总数;