135. 分发糖果
class Solution {
public:
int candy(vector<int>& ratings)
{
int len = ratings.size();
vector<int> left(len, 1);
vector<int> right(len, 1);
vector<int> count(len, 1);
for (int i = 1; i < len; ++i)
{
if (ratings[i] > ratings[i - 1])
{
left[i] = left[i - 1] + 1;
}
}
int sum = left[len - 1];
for (int i = len - 2; i >= 0; --i)
{
if (ratings[i] > ratings[i + 1])
{
right[i] = right[i + 1] + 1;
}
sum += max(left[i], right[i]);
}
return sum;
}
};
优化一点空间, 不要vector left
class Solution {
public:
int candy(vector<int>& ratings)
{
int len = ratings.size();
vector<int> left(len, 1);
vector<int> count(len, 1);
for (int i = 1; i < len; ++i)
{
if (ratings[i] > ratings[i - 1])
{
left[i] = left[i - 1] + 1;
}
}
int sum = left[len - 1];
int right = 1;
for (int i = len - 2; i >= 0; --i)
{
if (ratings[i] > ratings[i + 1])
{
right = right + 1;
}
else
right = 1;
sum += max(left[i], right);
}
return sum;
}
};
O(1)空间
class Solution {
public:
int candy(vector<int>& ratings)
{
int n = ratings.size();
int ret = 1;
int 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;
}
};
|