当前位置:网站首页>牛客网:分糖果问题
牛客网:分糖果问题
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;
}
};边栏推荐
- Sign up to open the third session of the "flying oar hacker marathon". It's been a long time
- 金仓数据库 KingbaseES 插件DBMS_UTILITY
- Netease's open source distributed storage system curve officially became the CNCF sandbox project
- Use of comparable (for arrays.sort)
- ARM64特有一些的汇编指令
- Ouverture de l'inscription | le troisième marathon des hackers de pagaie est arrivé comme prévu.
- Arrays.asList()
- 开源社邀请您参加OpenSSF开源安全线上研讨会
- 金仓KFS数据级联场景部署
- FPGA displays characters and pictures based on VGA
猜你喜欢

Apache ShenYu 入門
![[observation] objectscale: redefining the next generation of object storage, reconstruction and innovation of Dell Technology](/img/82/8cac87231e51698ab17f1274b3a0bd.jpg)
[observation] objectscale: redefining the next generation of object storage, reconstruction and innovation of Dell Technology

Shen Lu, China Communications Institute: police open source Protocol - ofl v1.1 Introduction and Compliance Analysis

Geographic location system based on openstreetmap+postgis paper documents + reference papers + project source code and database files

一个数学难题,难倒两位数学家

报名开启|飞桨黑客马拉松第三期如约而至,久等啦

基於Minifilter框架的雙緩沖透明加解密驅動 課程論文+項目源碼

ZABBIX distributed system monitoring

Android之Kotlin语法详解与使用

Redis6笔记02 配置文件,发布和订阅,新数据类型,Jedis操作
随机推荐
ARM64特有一些的汇编指令
金仓数据库 KingbaseES 插件DBMS_RANDOM
Multiple environment variables
如何实现移动端富文本编辑器功能
[shangyun boutique] energy saving and efficiency improvement! Accelerating the transformation of "intelligent manufacturing" in the textile industry
Bayes
zabbix分布式系统监控
16 enterprise architecture strategies
Gaussdb others scenarios with high memory
Arrays. asList()
A program reflecting the characteristics of C language program structure
Network remote access using raspberry pie
Tidb applicable scenarios
基於Minifilter框架的雙緩沖透明加解密驅動 課程論文+項目源碼
子类A继承父类B, A a = new A(); 则父类B构造函数、父类B静态代码块、父类B非静态代码块、子类A构造函数、子类A静态代码块、子类A非静态代码块 执行的先后顺序是?
Nuxtjs actual combat case
Spannable 和 Editable、SpannableString 和 SpannableString
CSRF attack
从GEE中免费获取全球人类住区层 (GHSL) 数据集
Is it safe for Guosen Securities to open a securities account