金融信创如何推动金融服务效率与安全的全面提升
760
2022-08-25
LeetCode-135. Candy
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?
Example 1:
Input: [1,0,2]Output: 5Explanation: You can allocate to the first, second and third child with 2, 1, 2 candies respectively.
Example 2:
Input: [1,2,2]Output: 4Explanation: 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.
题解:
贪心算法。
从前往后遍历如果第i + 1个权重大于i,则sum[i + 1] = sum[i] + 1。
从后往前遍历,如果 第i个权重大于i + 1并且sum[i]小于等于sum[i + 1],那么sum[i] = sum[i + 1] + 1。
class Solution {public: int candy(vector
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~