首页 > 其他 > 详细

Candy

时间:2016-02-22 20:42:05      阅读:233      评论:0      收藏:0      [点我收藏+]

题目:

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?

Cpp版本:

class Solution {
public:
    int candy(vector<int>& ratings) {
        int len = ratings.size();
        if (ratings.empty())
            return 0;

        if (len == 1)
            return 1;

        int *Candy = new int[len];
        Candy[0] = 1;
        for (int i = 1; i < len; i++) {
            if (ratings[i] > ratings[i - 1]) {
                Candy[i] = Candy[i - 1] + 1;
            } else {
                Candy[i] = 1;
            }
        }

        for (int i = len - 2; i >= 0; i--) {
            if (ratings[i] > ratings[i + 1] && Candy[i] <= Candy[i+1])
                Candy[i] = Candy[i + 1] + 1;
        }
        int ret = 0;
        for (int i = 0; i < len; i++) {
            ret += Candy[i];
        }
        return ret;
    }
};

Java:

public class Solution {
    public int candy(int[] ratings) {
        int size = ratings.length;
        if (size == 0)    return 0;
        if (size == 1)  return 1;

        int[] Candy = new int[size];

        Candy[0] = 1;
        for (int i = 1; i < size; i++) {
            if (ratings[i] > ratings[i - 1])
                Candy[i] = Candy[i - 1] + 1;
            else
                Candy[i] = 1;
        }

        for (int i = size - 2; i >= 0; i--) {
            if (ratings[i] > ratings[i + 1] && Candy[i] <= Candy[i + 1]) {
                Candy[i] = Candy[i + 1] + 1;
            }
        }

        int ret = 0;
        for (int i = 0; i < size; i++) {
            ret += Candy[i];
        }
        return ret;
    }
}

 

Candy

原文:http://www.cnblogs.com/wxquare/p/5207978.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!