leetcode135. Candy

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode135. 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?

问题如上。

先放上一种方法的实现,以下代码在不考虑数组越界的情况下可以输出正确结果。

 1 class Solution{
 2   public:
 3     int candy(vector<int> &ratings){
 4         int start = 0, end, count = 0; //start=right
 5         int candyCount[1000];          //储存每个人的糖果数量
 6         ratings.push_back(-1);
 7         if (ratings.size() == 2)    return 1;
 8         for (int i = 0; i < ratings.size(); ++i){
 9             if ((ratings[i] <= ratings[i - 1] && ratings[i] < ratings[i + 1]) || (i - 1 < 0 && ratings[i] < ratings[i + 1]) || (i + 1 > ratings.size() - 1 && ratings[i] < ratings[i - 1])){
10                 candyCount[i] = 1;
11                 end = i;
12                 if (end == start)   continue;
13                 vector<int>::iterator maxelem = max_element(ratings.begin() + start, ratings.begin() + end);
14                 int flag = std::distance(ratings.begin(), maxelem);
15                 for (int m = start + 1; m < flag; ++m)
16                     ratings[m] > ratings[m - 1] ? candyCount[m] = candyCount[m - 1] + 1 : candyCount[m] = candyCount[m - 1];
17                 for (int n = end - 1; n > flag; --n){
18                     ratings[n] > ratings[n + 1] ? candyCount[n] = candyCount[n + 1] + 1 : candyCount[n] = candyCount[n + 1];
19                     if ((end == ratings.size() - 1) && (n == end - 1))  candyCount[n]--;
20                 }
21                 if (ratings[flag] == ratings[flag + 1]){
22                     candyCount[flag - 1] < candyCount[flag + 1] ? candyCount[flag] = candyCount[flag + 1] : candyCount[flag] = candyCount[flag - 1] + 1;
23                     while ((ratings[flag] == ratings[flag + 1])&&(flag+1<ratings.size()))
24                         candyCount[flag + 1] = candyCount[flag++];
25                 }else{
26                     candyCount[flag - 1] > candyCount[flag + 1] ? candyCount[flag] = candyCount[flag - 1] + 1 : candyCount[flag] = candyCount[flag + 1] + 1;
27                 }
28                 start = i;
29             }
30         }
31         for (int k = 0; k < ratings.size() - 1; ++k)
32             count += candyCount[k];
33         return count;
34     }
35 };

写的又臭又长。。。

以上是关于leetcode135. Candy的主要内容,如果未能解决你的问题,请参考以下文章

leetcode135. Candy

leetcode135 - Candy - hard

Baozi Leetcode solution 135: Candy

LeetCode从零单排No.135Candy(双向动态规划)

Leetcode 135. Candy

[LeetCode] 135. 分发糖果