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?

 

思想:确定变量分析法,先确定一个变量,然后进行分析. 先确保一侧满足条件,然后来调整另外一侧。

java代码:

  1. public int candy(int[] ratings) {
  2. int rlen = ratings.length;
  3. if(rlen==0) return 0;
  4. if(rlen==1) return 1;
  5. int[] candy = new int[rlen];
  6. for(int i=0;i<rlen;i++) {
  7. candy[i] = 1;
  8. }
  9. for(int i=1;i<rlen;i++) {
  10. if(ratings[i] > ratings[i-1]) {
  11. candy[i] = candy[i-1] + 1;
  12. }
  13. }
  14. for(int j=rlen-2;j>=0;j--) {
  15. if(ratings[j] > ratings[j+1]) {
  16. candy[j] = Math.max(candy[j],candy[j+1]+1);
  17. }
  18. }
  19. int sum = 0;
  20. for(int i=0;i<rlen;i++) {
  21. sum+=candy[i];
  22. }
  23. return sum;
  24. }
posted @ 2014-07-14 22:22  purejade  阅读(107)  评论(0)    收藏  举报