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?

思路:

每个孩子默认分一颗糖;先从左往右扫,如果右边大于左边,但糖数小于等于左边,则右边的糖数是左边的加一;再从右往左扫,如果左边大于右边,但糖数小于等于右边,左边的糖数是右边的加一。最后求和。

代码:

 1     int candy(vector<int> &ratings) {
 2         // IMPORTANT: Please reset any member data you declared, as
 3         // the same Solution instance will be reused for each test case.
 4         int num = ratings.size();
 5         int result = 0;
 6         vector<int> candies(num, 1);
 7         for(int i = 1; i < num; i++){
 8             if(ratings[i] > ratings[i-1] && candies[i] <= candies[i-1])
 9                 candies[i] = candies[i-1]+1;
10         }
11         for(int i = num-2; i >= 0; i--){
12             if(ratings[i] > ratings[i+1] && candies[i] <= candies[i+1])
13                 candies[i] = candies[i+1]+1;
14         }
15         for(int i = 0; i < num; i++)
16             result += candies[i];
17         return result;
18     }

 

转载于:https://www.cnblogs.com/waruzhi/p/3444417.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值