标签:
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:
What is the minimum candies you must give?
Subscribe to see which companies asked this question
思路:
1.先给每个小孩分1 个candy;
2.从左往右:如果,左<右,则右边小孩加1颗candy;
2.从右往左:如果,左>右,则左边小孩要比右边的candy多。
java code:
public class Solution { public int candy(int[] ratings) { int len = ratings.length; int[] candies = new int[len]; for(int i=0;i<len;i++) candies[i] = 1; for(int i=1;i<len;i++) { if(ratings[i-1] < ratings[i]) candies[i] = candies[i-1] + 1; } for(int i=len-1;i>0;i--) { if(ratings[i-1] > ratings[i]) candies[i-1] = Math.max(candies[i-1], candies[i]+1); } int ans = 0; for(int candy : candies) { ans += candy; } return ans; } }
标签:
原文地址:http://blog.csdn.net/itismelzp/article/details/51502655