当前位置:网站首页>BM95 分糖果问题
BM95 分糖果问题
2022-06-21 16:05:00 【程序员·小李】
一群孩子做游戏,现在请你根据游戏得分来发糖果,要求如下:
1. 每个孩子不管得分多少,起码分到一个糖果。
2. 任意两个相邻的孩子之间,得分较多的孩子必须拿多一些糖果。(若相同则无此限制)
给定一个数组 arrarr 代表得分数组,请返回最少需要多少糖果。
要求: 时间复杂度为 O(n)O(n) 空间复杂度为 O(n)O(n)
每个人至少一个。
从左向右遍历一次,满足右侧的人。(类似于传声筒,从左向右遍历时,只关心是不是比自己左侧的高)

从右向左遍历一次,满足左侧的人。(类似于传声筒,从右向左遍历时,只关心是不是比自己右侧的高)

public int candy (int[] arr) {
// write code here
int[] result = new int[arr.length];
// 每人至少一个
for (int i = 0 ; i < result.length; i++){
result[i] = 1;
}
// 右边的比左边的分值高,得多分一个
for (int i = 1 ; i < arr.length; i++){
if (arr[i] > arr[i-1]){
result[i] = result[i-1] + 1;
}
}
// 左边的比右边的分值高
for (int i = arr.length - 1; i > 0; i--){
if (arr[i - 1] > arr[i]){
result[i - 1] = result[i-1] < result[i] + 1 ? result[i] + 1 : result[i-1];
}
}
int sum = 0;
for (int i = 0 ; i < result.length; i++){
sum += result[i];
}
return sum;
}注:从右向左遍历时,需要注意左侧分得的糖果已经比右侧大的可能性。
边栏推荐
- 贝叶斯公式的两种理解
- uni-app框架学习笔记
- How to connect the Internet - FTTH
- Design and implementation of face verification system for floating population management
- Force deduction solution summary 1108-ip address invalidation
- path.join() 、path.basename() 和 path.extname()
- The new razor component supports proxy connection to RDP, and jumpserver fortress v2.23.0 is released
- 3M mutual aid intelligent contract system development and construction technology
- 【mysql学习笔记12】分页查询
- Readjustment of move protocol beta to expand the total prize pool
猜你喜欢

Niuke.com: large number addition

Common formula of derivative__ Common formulas of indefinite integral
![[MySQL learning notes 15] user management](/img/e8/4773f99c42891789b0311506b8384f.png)
[MySQL learning notes 15] user management

程序员进修之路

Niuke network: verify the IP address

变量与指针

函数调用模型

Application of integrated servo motor and Schneider PLC tm241cec24t under CANopen Protocol

Qt5 knowledge: string list qstringlistmodel

Vector data download for mainland and global epidemic data, based on geo JSON to SHP
随机推荐
xlrd寻找指定内容所在行与行内容
Serialization and deserialization of binary tree
很多软件公司,其实都是“笑话”
函数调用模型
The fundamental task of Natural Science
Common formula of derivative__ Common formulas of indefinite integral
[MySQL learning notes 16] permission management
2022年第三届全国运筹学/数据、模型与决策课程教学研讨会通知
[MySQL learning notes 19] multi table query
exness:美国通货膨胀影响太大,美联储大佬纷纷表态
【mysql学习笔记12】分页查询
path. join() 、path. Basename() and path extname()
The beta version of move protocol is stable, and it is temporarily decided to expand the scale of the prize pool
Force deduction solution summary 1108-ip address invalidation
In the "roll out" era of Chinese games, how can small and medium-sized manufacturers solve the problem of going to sea?
Niuke network: verify the IP address
fs.readFile() 和 fs.writeFile()
go corn定时任务简单应用
Readjustment of move protocol beta to expand the total prize pool
kotlin 注解声明与使用