分发糖果
作者:互联网
老师想给孩子们分发糖果,有 N 个孩子站成了一条直线,老师会根据每个孩子的表现,预先给他们评分。
你需要按照以下要求,帮助老师给这些孩子分发糖果:
每个孩子至少分配到 1 个糖果。
评分更高的孩子必须比他两侧的邻位孩子获得更多的糖果。
那么这样下来,老师至少需要准备多少颗糖果呢?
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/candy
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Solution {
public int candy0(int[] ratings) {
if (ratings == null || ratings.length == 0) {
return 0;
}
int n = ratings.length;
int[] left = new int[n];
int[] right = new int[n];
left[0] = 1;
for (int i = 1; i < n; ++i) {
if (ratings[i] > ratings[i - 1]) {
left[i] = left[i - 1] + 1;
} else {
left[i] = 1;
}
}
right[n - 1] = 1;
for (int i = n - 2; i >= 0; --i) {
if (ratings[i] > ratings[i + 1]) {
right[i] = right[i + 1] + 1;
} else {
right[i] = 1;
}
}
int ret = 0;
for (int i = 0; i < n; ++i) {
ret += Math.max(left[i], right[i]);
}
return ret;
}
public int candy(int[] ratings) {
if (ratings == null || ratings.length == 0) {
return 0;
}
int n = ratings.length;
int ret = 1, inc = 1, dec = 0, pre = 1;
for (int i = 1; i < n; ++i) {
if (ratings[i] >= ratings[i - 1]) {
dec = 0;
pre = ratings[i] == ratings[i - 1] ? 1 : pre + 1;
ret += pre;
inc = pre;
} else {
dec++;
if (dec == inc) {
dec++;
}
ret += dec;
pre = 1;
}
}
return ret;
}
}
标签:pre,分发,right,ratings,int,ret,糖果,left 来源: https://www.cnblogs.com/tianyiya/p/15478980.html