[LeetCode] Candy

简介: Well, you may need to run some examples to have the intuition for the answer since we only require children with higher rating get more candies than their neighbors, not all those with lower ratings.

Well, you may need to run some examples to have the intuition for the answer since we only require children with higher rating get more candies than their neighbors, not all those with lower ratings.

The following code is taken from this link. It involves two-pass scan to ensure the above condition. You will get it after running some examples, like modifying the code and check the wrong cases :-)

 1 class Solution {
 2 public:
 3     int candy(vector<int>& ratings) {
 4         int n = ratings.size();
 5         vector<int> candies(n, 1);
 6         for (int i = 1; i < n; i++)
 7             if (ratings[i] > ratings[i - 1])
 8                 candies[i] = candies[i - 1] + 1;
 9         for (int i = n - 1; i > 0; i--)
10             if (ratings[i - 1] > ratings[i])
11                 candies[i - 1] = max(candies[i - 1], candies[i] + 1);
12         int total = 0;
13         for (int i = 0; i < n; i++)
14             total += candies[i];
15         return total;
16     }
17 };

 

目录
相关文章
|
机器学习/深度学习 算法
代码随想录Day25 回溯算法 LeetCode T51 N皇后问题
代码随想录Day25 回溯算法 LeetCode T51 N皇后问题
72 1
|
4月前
|
机器学习/深度学习 算法 C++
Leetcode第52题(N皇后II)
这篇文章介绍了解决LeetCode第52题(N皇后II)的C++代码实现,使用深度优先搜索(DFS)算法来找出所有可能的解决方案,并计算出不同的解决方案数量。
33 1
|
机器学习/深度学习 算法 安全
LeetCode - #52 N皇后 II
不积跬步,无以至千里;不积小流,无以成江海,Swift社区 伴你前行。如果大家有建议和意见欢迎在文末留言,我们会尽力满足大家的需求。
LeetCode - #52 N皇后 II
LeetCode 135. Candy
老师想给孩子们分发糖果,有 N 个孩子站成了一条直线,老师会根据每个孩子的表现,预先给他们评分。 你需要按照以下要求,帮助老师给这些孩子分发糖果: 每个孩子至少分配到 1 个糖果。 相邻的孩子中,评分高的孩子必须获得更多的糖果。 那么这样下来,老师至少需要准备多少颗糖果呢?
52 0
LeetCode 135. Candy
|
存储 Go
新年快乐题解
新年快乐题解
112 0
新年快乐题解
|
SQL 前端开发 小程序
【边学边敲边记】LeetCode012:反转字符串
【边学边敲边记】LeetCode012:反转字符串
128 0
【边学边敲边记】LeetCode012:反转字符串
|
算法 索引
LeetCode每日一练(杨辉三角)
LeetCode每日一练(杨辉三角)
178 0
LeetCode每日一练(杨辉三角)
|
算法 前端开发 程序员
「LeetCode」198-打家劫舍⚡️
「LeetCode」198-打家劫舍⚡️
136 0
「LeetCode」198-打家劫舍⚡️