当前位置:网站首页>Niuke.com: Candy distribution
Niuke.com: Candy distribution
2022-06-25 11:24:00 【lsgoose】
This question is numb , At least... Is given in the stem , In fact, it is obvious to use greed .
So how can we be greedy , as everyone knows , At least it is 1, We naturally think of , Next to him , If you're older than him , Then add at least one to ensure the minimum , With this concept , We can talk about the idea of this problem .
Let's first look from left to right , Assume that everything is as long as 1, If the current number is larger than the previous number , So we just add one to the minimum number of candies , Otherwise, it will not be dealt with .
It's obvious that , We cannot guarantee that if the current number is larger than the following , But the number of sweets is also bigger than that of the later , Because we only looked at the comparison between the current number and the previous number for the first time .
To fix , We need to look again from right to left , If the current number is larger than the right , And the number of sweets is less than or equal to that on the right ( The reason for taking equals is that we didn't deal with the equals sign in the first traversal )
The code is as follows :
class Solution {
public:
/**
* pick candy
* @param arr int integer vector the array
* @return int integer
*/
int candy(vector<int>& arr) {
// write code here
int n=arr.size();
vector<int> num(n, 1);
for(int i=1;i<n;++i){
if(arr[i]>arr[i-1]){
num[i]=num[i-1]+1;
}
}
int res=num[n-1];
for(int i=n-2;i>=0;i--){
if(arr[i]>arr[i+1] && num[i]<num[i+1]){
num[i]=num[i+1]+1;
}
res+=num[i];
}
return res;
}
};
边栏推荐
- Technical practice and development trend of video conference all in one machine
- 牛客网:旋转数组
- MySQL and Oracle processing CLOB and blob fields
- 牛客网:分糖果问题
- 反应c语言程序结构特点的程序
- Simple use of SVN
- Gaussdb others scenarios with high memory
- 建造者模式
- Shen Lu, China Communications Institute: police open source Protocol - ofl v1.1 Introduction and Compliance Analysis
- Detailed explanation of Spark's support source code for Yan priority
猜你喜欢
随机推荐
Comparison between relu and SIGMOD
At 16:00 today, Mr. sunxiaoming, a researcher of the Institute of computing, Chinese Academy of Sciences, took you into the quantum world
中國信通院沈瀅:字體開源協議——OFL V1.1介紹及合規要點分析
Vulnérabilité à l'injection SQL (contournement)
基於Minifilter框架的雙緩沖透明加解密驅動 課程論文+項目源碼
金仓数据库 KingbaseES 插件dbms_session
寿命分布 4种
金仓数据库 KingbaseES 插件DBMS_UTILITY
西山科技冲刺科创板:拟募资6.6亿 郭毅军夫妇有60%表决权
一个数学难题,难倒两位数学家
金仓数据库 KingbaseES 插件force_view
Kingbasees plug-in DBMS of Jincang database_ UTILITY
金仓数据库 KingbaseES 插件ftutilx
Detection and analysis of simulator in an app
Handler、Message、Looper、MessageQueue
金仓数据库 KingbaseES 插件identity_pwdexp
An interesting logic SRC mining
[shangyun boutique] energy saving and efficiency improvement! Accelerating the transformation of "intelligent manufacturing" in the textile industry
GaussDB 如何统计用户sql的响应时间
Leetcode 1249. Remove invalid brackets (awesome, finally made)