LeetCode-135. Candy

网友投稿 704 2022-08-25

LeetCode-135. Candy

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& ratings) { int n = ratings.size(); int res = 0; vector sum(n, 1); for (int i = 0; i < n - 1; i++) { if (ratings[i + 1] > ratings[i]) { sum[i + 1] = sum[i] + 1; } } for (int i = n - 2; i >= 0; i--) { if (ratings[i] > ratings[i + 1] && sum[i] <= sum[i + 1]) { sum[i] = sum[i + 1] + 1; } } for (int i = 0; i < n; i++) { res += sum[i]; } return res; }};

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:华为-图片整理
下一篇:构建高并发高可用的电商平台架构实践(一)——设计理念(电商平台搭建构思)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~