LeetCode 135 Candy (C++, Python)

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?

Solution C++


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution {
public:
    int candy(vector<int>& ratings) {
        if (ratings.size() < 2) return ratings.size();
        vector<int> candy(ratings.size(), 1);
        for (int i = 1; i < candy.size(); ++i) {
            if (ratings[i] > ratings[i - 1]) candy[i] = candy[i - 1] + 1;   
        }
        for (int i = candy.size() - 2; i >= 0; --i) {
            if (ratings[i] > ratings[i + 1] && candy[i] <= candy[i + 1]) candy[i] = candy[i + 1] + 1;
        }
        return accumulate(candy.begin(), candy.end(), 0);
    }
};

Solution Python


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution:
    # @param {integer[]} ratings
    # @return {integer}
    def candy(self, ratings):
        if len(ratings) < 2: return len(ratings)
        candy = [1] * len(ratings)
        for i in range(1, len(candy)):
            if ratings[i] > ratings[i - 1]:
                candy[i] = candy[i - 1] + 1
        for i in range(len(candy) - 2, -1, -1):
            if ratings[i] > ratings[i + 1] and candy[i] <= candy[i + 1]:
                candy[i] = candy[i + 1] + 1
        return reduce(lambda x, y: x + y, candy)

Popular posts from this blog

How Django Works (4) URL Resolution

Python Class Method and Class Only Method

How Django works (3): Testing Server and Static Files Serving