135. Candy

网友投稿 488 2022-11-11

135. Candy

135. Candy

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?

class Solution public int candy(int[] ratings) { int sum = 0; int[] left2right = new int[ratings.length]; int[] right2left = new int[ratings.length]; Arrays.fill(left2right, 1); Arrays.fill(right2left, 1); for (int i = 1; i < ratings.length; i++) { if (ratings[i] > ratings[i - 1]) { left2right[i] = left2right[i - 1] + 1; } } for (int i = ratings.length - 2; i >= 0; i--) { if (ratings[i] > ratings[i + 1]) { right2left[i] = right2left[i + 1] + 1; } } for (int i = 0; i < ratings.length; i++) { sum += Math.max(left2right[i], right2left[i]); } return sum; }}

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:maven配置文件pom增加变量取版本号方式
下一篇:145. Binary Tree Postorder Traversal
相关文章

 发表评论

暂时没有评论,来抢沙发吧~