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?

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;
    }
}

 

posted @ 2016-02-22 19:07  wxquare  阅读(230)  评论(0编辑  收藏  举报