当前位置:网站首页>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 .
边栏推荐
- Stackoverflow 年度报告 2022:开发者最喜爱的数据库是什么?
- Material management system based on SSM (source code + document + database)
- Docker deploy mysql5.7
- RF_DC系统时钟设置GEN1/GEN2
- Teach you how to view the number of connected people on WiFi in detail how to view the number of connected people on WiFi
- Huawei cloud modelarts has ranked first in China's machine learning public cloud service market for the fourth time!
- [cann document express issue 06] first knowledge of tbe DSL operator development
- Vxlan and MPLS: from data center to Metro Ethernet
- 云计算发展的 4 个阶段,终于有人讲明白了
- IDEA Dashboard
猜你喜欢

Nodered has no return value after successfully inserting into the database (the request cannot be ended)

大一女生废话编程爆火!懂不懂编程的看完都拴Q了

在Dialog中使用透明的【X】叉叉按钮图片

物聯網?快來看 Arduino 上雲啦

Sequence stack version 1.0

顺序表的基本操作

苹果、微软、谷歌不再掐架,今年要合力干一件大事

基于QT+MySQL的相机租赁管理系统

Dongyuhui is not enough to bring goods to "rescue" live broadcast
![[普通物理] 光栅衍射](/img/f3/965ff7cd3bb76b4f71b69b9d12ece3.png)
[普通物理] 光栅衍射
随机推荐
Byte and Tencent have also come to an end. How fragrant is this business of "making 30million yuan a month"?
全上链哈希游戏dapp系统定制(方案设计)
物联网?快来看 Arduino 上云啦
红象云腾完成与龙蜥操作系统兼容适配,产品运行稳定
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
Accurate calculation of task progress bar of lol mobile game
The first public available pytorch version alphafold2 is reproduced, and Columbia University is open source openfold, with more than 1000 stars
Docker deploy mysql5.7
The AI for emotion recognition was "harbouring evil intentions", and Microsoft decided to block it!
在Dialog中使用透明的【X】叉叉按钮图片
Basic concepts and definitions of Graphs
First understand redis' data structure - string
Stackoverflow 年度报告 2022:开发者最喜爱的数据库是什么?
Fundamentals of performance testing -- definitions of common terms
两位湖南老乡,联手干出一个百亿IPO
实现基于Socket自定义的redis简单客户端
苹果、微软、谷歌不再掐架,今年要合力干一件大事
The four stages of cloud computing development have finally been clarified
C language to realize mine sweeping (simple version)
Error in Android connection database query statement