题目描述(Hard)
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?
题目链接
https://leetcode.com/problems/candy/description/
Example 1:
Input: [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: [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.
算法分析
先从左到右,再从右到左遍历,时间复杂度
,空间复杂度
。
提交代码:
class Solution {
public:
int candy(vector<int>& ratings) {
const int size = ratings.size();
vector<int> candy(size, 1);
// left -> right
for (int i = 0; i < size - 1; ++i)
{
if (ratings[i + 1] > ratings[i])
candy[i + 1] = candy[i] + 1;
}
// right -> left
for (int i = size - 1; i > 0; --i)
{
if (ratings[i - 1] > ratings[i])
candy[i - 1] = max(candy[i] + 1, candy[i - 1]);
}
return accumulate(candy.begin(), candy.end(), 0);
}
};
测试代码:
// ====================测试代码====================
void Test(const char* testName, vector<int>& ratings, int expected)
{
if (testName != nullptr)
printf("%s begins: \n", testName);
Solution s;
int result = s.candy(ratings);
if (result == expected)
printf("passed\n");
else
printf("failed\n");
}
int main(int argc, char* argv[])
{
vector<int> ratings = { 1, 0, 2 };
Test("Test1", ratings, 5);
ratings = { 1, 2, 2 };
Test("Test2", ratings, 4);
ratings = { 1, 3, 4, 5, 2 };
Test("Test3", ratings, 11);
return 0;
}