当前位置:网站首页>Bm95 points candy problem
Bm95 points candy problem
2022-06-21 17:37:00 【Programmer Xiao Li】
A group of children play games , Now please give out candy according to the score of the game , Requirements are as follows :
1. No matter how much each child scores , At least one candy .
2. Between any two adjacent children , Children who score more must take more candy .( If the same, there is no such restriction )
Given an array arrarr Represents the score array , Please return the minimum number of sweets needed .
requirement : The time complexity is O(n)O(n) The space complexity is O(n)O(n)
Everyone has at least one .
Traverse once from left to right , Meet the people on the right .( Similar to a microphone , When traversing from left to right , Only care about whether it is higher than the one on your left )

Traverse once from right to left , Meet the people on the left .( Similar to a microphone , From right to left , Only care about whether it is higher than the one on your right )

public int candy (int[] arr) {
// write code here
int[] result = new int[arr.length];
// At least one per person
for (int i = 0 ; i < result.length; i++){
result[i] = 1;
}
// The score on the right is higher than that on the left , One more point
for (int i = 1 ; i < arr.length; i++){
if (arr[i] > arr[i-1]){
result[i] = result[i-1] + 1;
}
}
// The score on the left is higher than that on the right
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;
}notes : From right to left , It should be noted that the left side is more likely to get candy than the right side .
边栏推荐
- IEC62133与EN62133有何区别?主要测试哪些项目?
- List set map in kotlin
- 【Leetcode】297. Serialization and deserialization of binary tree (difficult)
- 关于xlrd库的基础操作(新手向)
- My gadget - card learning app is complete
- 【mysql学习笔记11】排序查询
- 焱融科技 YRCloudFile 与安腾普完成兼容认证,共创存储新蓝图
- The node server res.end() writes Chinese, and the solution to the problem of garbled code in the client
- fs. Readfile() and fs writeFile()
- #Vscode工具#
猜你喜欢
随机推荐
In the "roll out" era of Chinese games, how can small and medium-sized manufacturers solve the problem of going to sea?
算法--按奇偶性交换后的最大数字(Kotlin)
Stack growth direction and memory growth direction
#Vscode工具#
fs.readFile() 和 fs.writeFile()
导数常用公式__不定积分常用公式
RTMP webrtc protocol OpenSSL installation
我的小工具-卡片学习APP 完成啦
Vector data download for mainland and global epidemic data, based on geo JSON to SHP
钣金行业MES系统的特色需求
The next stop of Intelligent Manufacturing: cloud native + edge computing two wheel drive
[Error] ‘vector‘ was not declared in this scope
《MATLAB 神经网络43个案例分析》:第27章 LVQ神经网络的预测——人脸朝向识别
The main relations and differences between Poisson sampling and Bernoulli sampling
variable
Not this year's 618?
一招教你通过焱融 SaaS 数据服务平台+ELK 让日志帮你做决策
clickhouse学习笔记2:基本使用教程
变量与指针
【mysql学习笔记15】用户管理









