【LeetCode】22.Candy

博客围绕LeetCode上的糖果分配问题展开,该问题要求给一排孩子分糖果,每个孩子至少一颗,评分高的孩子比邻居糖果多,需计算最少糖果数。给出了示例及输入输出,还提及算法是先从左到右、再从右到左遍历,并给出了提交和测试代码。

题目描述(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.

算法分析

先从左到右,再从右到左遍历,时间复杂度O(n),空间复杂度O(n)

提交代码:

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;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值