当前位置:网站首页>Leetcode (135) - distribute candy
Leetcode (135) - distribute candy
2022-06-24 20:34:00 【SmileGuy17】
Leetcode(135)—— Distribute candy
subject
n Two kids in a row . Give you an array of integers ratings Indicates the score of each child .
You need to follow these requirements , Distribute candy to these children :
- Each child is assigned at least 1 A candy .
- Children with higher scores from two adjacent children will get more candy .
- Please distribute candy to each child , Calculate and return what needs to be prepared Minimum number of sweets .
Example 1:
Input :ratings = [1,0,2]
Output :5
explain : You can give the first one separately 、 the second 、 The third child distributed 2、1、2 Candy .
Example 2:
Input :ratings = [1,2,2]
Output :4
explain : You can give the first one separately 、 the second 、 The third child distributed 1、2、1 Candy .
The third child only got 1 Candy , This satisfies two conditions in the problem surface .
Tips :
- n == ratings.length
- 1 1 1 <= n <= 2 ∗ 1 0 4 2 * 10^4 2∗104
- 0 0 0 <= ratings[i] <= 2 ∗ 1 0 4 2 * 10^4 2∗104
Answer key
Method 1 : Greedy Algorithm
Ideas
We can 「 Among the neighboring children , Children with high scores must get more candy 」 This sentence is split into two rules , Deal with... Separately .
- The left rule : When ratings [ i − 1 ] < ratings [ i ] \textit{ratings}[i - 1] < \textit{ratings}[i] ratings[i−1]<ratings[i] when , i i i Student No. 1 will have more candy than i − 1 i - 1 i−1 There are a lot of sweets for child No .
- Local optimum : As long as the score on the right is greater than that on the left , The child on the right has one more candy c a n d y V e c [ i ] = c a n d y V e c [ i − 1 ] + 1 candyVec[i] = candyVec[i - 1] + 1 candyVec[i]=candyVec[i−1]+1;
- The best in the world : Among the neighboring children , The right child with a high score gets more candy than the left child
- Right rule : When ratings [ i ] > ratings [ i + 1 ] \textit{ratings}[i] > \textit{ratings}[i + 1] ratings[i]>ratings[i+1] when , i i i Student No. 1 will have more candy than i + 1 i + 1 i+1 There are a lot of sweets for child No .
- Local optimum : take c a n d y V e c [ i + 1 ] + 1 candyVec[i + 1] + 1 candyVec[i+1]+1 and c a n d y V e c [ i ] candyVec[i] candyVec[i] The largest amount of candy , Guarantee No. i i i The number of sweets for a child is greater than that on the left and also greater than that on the right ;
- The best in the world : Among the neighboring children , Children with high scores get more candy .
We iterate over the array twice , When each student meets the left rule or the right rule , The minimum number of sweets to be shared . The number of sweets each person eventually gets is the maximum of the two numbers .
In particular , Take the left rule for example : We iterate through the array from left to right , Assume that the current traversal reaches the position i i i, If there is ratings [ i − 1 ] < ratings [ i ] \textit{ratings}[i - 1] < \textit{ratings}[i] ratings[i−1]<ratings[i] that i i i Student No. 1 will have more candy than i - 1i−1 There are a lot of sweets for child No , We make left [ i ] = left [ i − 1 ] + 1 \textit{left}[i] = \textit{left}[i - 1] + 1 left[i]=left[i−1]+1 that will do , Or we will order left [ i ] = 1 \textit{left}[i] = 1 left[i]=1.
In real code , Let's calculate the left rule first left \textit{left} left Array , When calculating the right rule, you only need to record the right rule of the current position with a single variable , Calculate the answer at the same time .

Why to take the maximum value is the right thinking :
We take any two points in the sequence ,A B
- If A > B , Then it is processed according to the left rule ,B No comparison A many ; After processing according to the right rule ,A Certain ratio B many , that A It will be updated ( Bigger ), but L、R The rules still hold :B No comparison A many ,A Certain ratio B many ;
- Similarly, we can discuss A<B;
- When A == B,A、B The value of is updated anyway , It doesn't affect L、R The rules
Sum up , The maximum value does not affect the establishment of a rule .
Code implementation
class Solution {
public:
int candy(vector<int>& ratings) {
int kid, size = ratings.size();
vector<int> num(size, 1);
kid = 1;
while(kid < size){
if(ratings[kid-1] < ratings[kid]) num[kid] = num[kid-1] + 1;
kid++;
}
kid = size-1;
while(kid > 0){
if(ratings[kid-1] > ratings[kid]) num[kid-1] = max(num[kid-1], num[kid] + 1);
kid--;
}
return accumulate(num.begin(), num.end(), 0);
}
};
Complexity analysis
Time complexity : O ( n ) O(n) O(n), among n n n It's the number of children . We need to traverse the array twice to calculate the minimum number of sweets that satisfy the left rule or the right rule, respectively .
Spatial complexity : O ( n ) O(n) O(n), among n n n It's the number of children . We need to save the number of sweets corresponding to all the left rules .
Method 2 : Constant space complexity
Ideas
be aware Candy is always given as little as possible , And from 1 1 1 Start to accumulate , Each time, you can give one more than the neighboring students , Or reset it to 1 1 1. According to this rule , We can draw the following figure :

The height of the histogram with the same color is always just 1 , 2 , 3 … 1,2,3 \dots 1,2,3….
And the height is not necessarily in ascending order , It could be … 3 , 2 , 1 \dots 3,2,1 …3,2,1 In descending order of :

Notice in the figure above , For the third student , It can be considered as green Ascending part , It can also be considered blue Descending part . because He also scored higher than the students on both sides . Let's modify the sequence a little , Here is the new sequence —— We noticed that The descending part on the right becomes longer ( from 3 Change into 4), The third student had to be assigned 4 4 4 A candy .

According to the law summarized above , We can propose a solution to this problem : We enumerate each student from left to right , Remember that the number of sweets given to the former student is pre \textit{pre} pre:
- If the current student scores higher than the previous student , It means that we are in the latest increasing sequence , Directly assigned to the student pre + 1 \textit{pre} + 1 pre+1 Just a candy .
- Otherwise we are in a decreasing sequence , We directly assign a candy to the current student , And all the students in the decreasing sequence of the student are assigned another candy , To ensure that the quantity of candy still meets the conditions .
- We don't need to explicitly allocate extra candy , Just record the current decreasing sequence length , Then you can know the amount of candy that needs to be distributed .
- At the same time, pay attention to when When the current decreasing sequence is the same length as the previous increasing sequence , You need to merge the last student of the nearest increasing sequence into the decreasing sequence .
such , We just record the length of the current decreasing sequence dec \textit{dec} dec, The length of the most recent increment sequence inc \textit{inc} inc The number of sweets shared with the previous student pre \textit{pre} pre that will do .
Code implementation
class Solution {
public:
int candy(vector<int>& ratings) {
int n = ratings.size();
int ret = 1;
int inc = 1, dec = 0, pre = 1;
for (int i = 1; i < n; i++) {
if (ratings[i] >= ratings[i - 1]) {
dec = 0;
pre = ratings[i] == ratings[i - 1] ? 1 : pre + 1;
ret += pre;
inc = pre;
} else {
dec++;
if (dec == inc) {
dec++;
}
ret += dec;
pre = 1;
}
}
return ret;
}
};
Complexity analysis
Time complexity : O ( n ) O(n) O(n), among n n n It's the number of children . We need to traverse the array twice to calculate the minimum number of sweets that satisfy the left rule or the right rule, respectively .
Spatial complexity : O ( 1 ) O(1) O(1), We just need a constant space to hold a few variables .
边栏推荐
- 顺序栈遍历二叉树
- 得物多活架构设计之路由服务设计
- Freshman girls' nonsense programming is popular! Those who understand programming are tied with Q after reading
- CVPR 2022缅怀孙剑!同济、阿里获最佳学生论文奖,何恺明入围
- OpenVINO2022 Dev Tools安装与使用
- Material management system based on SSM (source code + document + database)
- 2022年最新四川建筑八大员(电气施工员)模拟题库及答案
- Predicate
- Berkeley, MIT, Cambridge, deepmind et d'autres grandes conférences en ligne: vers une IA sûre, fiable et contrôlable
- 伯克利、MIT、劍橋、DeepMind等業內大佬線上講座:邁向安全可靠可控的AI
猜你喜欢

虚拟化是什么意思?包含哪些技术?与私有云有什么区别?

微信小程序自定义tabBar

16个优秀业务流程管理工具

图像PANR

Behind Tiantian Jianbao storm: tens of millions in arrears, APP shutdown, and the founder's premeditated plan to run away?

实现基于Socket自定义的redis简单客户端

Basic properties and ergodicity of binary tree

图的基本概念以及相关定义

When querying the database with Gorm, reflect: reflect flag. mustBeAssignable using unaddressable value

微信小程序中使用vant组件
随机推荐
等保备案是等保测评吗?两者是什么关系?
图像PANR
JMeter environment deployment
传统的IO存在什么问题?为什么引入零拷贝的?
Compressed list of redis data structures
With its own cells as raw materials, the first 3D printing ear transplantation was successful! More complex organs can be printed in the future
Coinbase将推出首个针对个人投资者的加密衍生产品
别再用 System.currentTimeMillis() 统计耗时了,太 Low,StopWatch 好用到爆!
等等党们的胜利!挖矿退潮后,显卡价格全面暴跌
Huawei cloud modelarts has ranked first in China's machine learning public cloud service market for the fourth time!
Sequence stack version 1.0
[普通物理] 光栅衍射
顺序栈遍历二叉树
unity之模糊背景(带你欣赏女人的朦胧美)
[suggested collection] time series prediction application and paper summary
It is said that Tencent officially announced the establishment of "XR" department to bet on yuanuniverse; Former CEO of Google: the United States is about to lose the chip competition. We should let T
Bytebase 加入阿裏雲 PolarDB 開源數據庫社區
The name of the button in the Siyuan notes toolbar has changed to undefined. Has anyone ever encountered it?
托管服务与SASE,纵享网络与安全融合 | 一期一会回顾
《梦华录》“超点”,鹅被骂冤吗?