当前位置:网站首页>牛客网:分糖果问题
牛客网:分糖果问题
2022-06-25 11:10:00 【lsgoose】
这题麻,题干中给出了最少,其实很明显要用贪心了。
那么我们如何来贪心呢,众所周知,最少其实就是1,我们很自然想到,和他相邻的,如果比他大,那就最少加一即可保证最小,有了这个概念,我们可以来谈谈这题的思路。
我们首先从左往右看,假定所有都只要1,如果当前数比前一个数要大,那么我们就直接用前面的最小糖果数加一,否则不处理。
这样一遍后很明显,我们无法保证如果当前数比后面大,但是糖果数也比后面大这么一件事,因为我们第一遍是只看了当前数和前面数的比较。
为了修正,我们需要从右往左再看一遍,如果当前数比右边大,而且糖果数是小于等于右边的(取等于是因为第一次遍历的时候我们并没有处理等于号)
代码如下所示:
class Solution {
public:
/**
* pick candy
* @param arr int整型vector the array
* @return int整型
*/
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;
}
};
边栏推荐
- 16 enterprise architecture strategies
- Socket communication principle
- Gaussdb cluster maintenance case set - slow SQL execution
- Daily 3 questions (3) - check whether integers and their multiples exist
- 贝叶斯
- Handler、Message、Looper、MessageQueue
- Apache ShenYu 入门
- ZABBIX distributed system monitoring
- 金仓KFS数据级联场景部署
- Handling of NPM I installation problems
猜你喜欢
记一次有趣的逻辑SRC挖掘
Database Series: MySQL index optimization summary (comprehensive version)
SQL注入漏洞(类型篇)
Socket communication principle
基于OpenStreetMap+PostGIS的地理位置系统 论文文档+参考论文文献+项目源码及数据库文件
Crawler scheduling framework of scratch+scratch+grammar
XSS attack
Double buffer transparent encryption and decryption driven course paper + project source code based on minifilter framework
中国信通院沈滢:字体开源协议——OFL V1.1介绍及合规要点分析
scrapy+scrapyd+gerapy 爬虫调度框架
随机推荐
Coscon'22 lecturer solicitation order
Jincang KFS data cascade scenario deployment
How gaussdb counts the response time of user SQL
Android:kotlin中Gson与JSON的泛型映射解析
[shangyun boutique] energy saving and efficiency improvement! Accelerating the transformation of "intelligent manufacturing" in the textile industry
Getting started with Apache Shenyu
Redis6笔记02 配置文件,发布和订阅,新数据类型,Jedis操作
XSS attack
Use of comparable (for arrays.sort)
Jincang database kingbasees plug-in force_ view
Apache ShenYu 入門
每日3题(2)- 找出数组中的幸运数
子类A继承父类B, A a = new A(); 则父类B构造函数、父类B静态代码块、父类B非静态代码块、子类A构造函数、子类A静态代码块、子类A非静态代码块 执行的先后顺序是?
zabbix分布式系统监控
scrapy+scrapyd+gerapy 爬虫调度框架
Gaussdb cluster maintenance case set - slow SQL execution
中國信通院沈瀅:字體開源協議——OFL V1.1介紹及合規要點分析
A random number generator
Is it safe to open an account through mobile phone if you open an account through stock speculation? Who knows?
金仓KFS数据级联场景部署