问题:
难度:hard
说明:
给出一个孩子分数列表,然后你分配糖果,要求每个孩子得到的糖果比相邻的孩子分数低的要多,要求返回最少所需糖果数量。
规则:
1、每个孩子至少有一个糖果
2、高孩子比相邻的低分孩子糖果都多
题目连接:https://leetcode.com/problems/candy/
输入范围:
n == ratings.length
1 <= n <= 2 * 104
0 <= ratings[i] <= 2 * 104
输入案例:
Example 1:
Input: ratings = [1,0,2]
Output: 5
Explanation: You can allocate to the first, second and third child with 2, 1, 2 candies respectively.
Example 2:
Input: ratings = [1,2,2]
Output: 4
Explanation: You can allocate to the first, second and third child with 1, 2, 1 candies respectively.
The third child gets 1 candy because it satisfies the above two conditions.
我的代码:
要求最少糖果数量,那么比相邻孩子分数高的孩子,只需要比相邻孩子糖果最多的 + 1 个糖果就行了。
有这么个数据问题比如:[1, 2, 9, 4, 3, 2, 1],我首先给前三个孩子糖果是 [1, 2, 3],然后再往后给就发生这样 [1, 2, 3, 4, 3, 2, 1] 分数 9 孩子和 分数 4 孩子相邻,但是要符合规则2 的话,就得要改变糖果的分配 [1, 2, 5, 4, 3, 2, 1]
说白了,就是分数从低往高排列就容易 +1 处理,但是从高往低分配,就得注意增长问题,那如果往低分配,每次遇到低的分数都 + 1 然后还得往前迭代 + 1,这样时间复杂度就高了。
为了偷懒,我把场景都改成从低往高统计就可以了,我不去想从高往低的问题。
1、先正序比较一次,只统计从低往高的
2、反序比较一次,同样只比较从低往高,但是要比较一下之前的值,取比较的最大值。
Java:
class Solution {
public int candy(int[] ratings) {
boolean h = false;
int res = 0;
int[] tmp = new int[ratings.length];
for(int i = 0, len = ratings.length, num = 1; i < len; i ++, num = 1) {
if(i - 1 >= 0 && ratings[i - 1] < ratings[i]) num = tmp[i - 1] + 1;
tmp[i] = num;
res += num;
}
for(int i = ratings.length, num = 1, len = ratings.length; i -- > 0; num = 1) {
if(i + 1 < len && ratings[i] > ratings[i + 1]) num = tmp[i + 1] + 1;
num = Math.max(num, tmp[i]);
res += num - tmp[i];
tmp[i] = num;
}
return res;
}
}
C++:
class Solution {
public:
int candy(vector<int>& ratings) {
int res = 0;
vector<int> tmp;
for(int i = 0, num = 1, size = ratings.size(); i < size; i ++, num = 1) {
if(i - 1 >= 0 && ratings[i] > ratings[i - 1]) num = tmp[i - 1] + 1;
tmp.push_back(num);
res += num;
}
for(int i = ratings.size(), num = 1, size = ratings.size(); i -- > 0; num = 1) {
if(i + 1 < size && ratings[i] > ratings[i + 1]) num = tmp[i + 1] + 1;
num = max(tmp[i], num);
res += num - tmp[i];
tmp[i] = num;
}
return res;
}
};