【leetcode】Candy
There are N children standing in a line. Each child is assigned a rating value.
You are giving candies to these children subjected to the following requirements:
- Each child must have at least one candy.
- Children with a higher rating get more candies than their neighbors.
What is the minimum candies you must give?
题解:
- 第一个孩子给一颗糖,然后从左到右遍历rate数组,如果孩子i+1的rate比孩子i的rate高,那么孩子i+1得到的糖果数目比孩子i得到的糖果数目多1;如果孩子i+1的rate比孩子i的rate低,那么就给孩子i+1一颗糖;
- 从右往左遍历rate数组,如果当前遍历的孩子i的rate比他右边的孩子的rate高,那么他得到的糖果就比他右边的孩子得到的糖果多1.
- 累加rate中所有的值,得到总的最少糖果数目。
代码如下:
1 public class Solution { 2 public int candy(int[] ratings) { 3 if(ratings.length == 0) 4 return 0; 5 6 int[] count = new int[ratings.length]; 7 Arrays.fill(count, 1); 8 9 for(int i = 1;i <= ratings.length-1;i++){ 10 if(ratings[i]> ratings[i-1] ) 11 count[i] = count[i-1] + 1; 12 } 13 14 int sum = 0; 15 for(int i = ratings.length-1;i >= 1;i--){ 16 sum += count[i]; 17 if(ratings[i-1] > ratings[i] && count[i-1] <= count[i]) 18 count[i-1] = count[i]+ 1; 19 } 20 21 return count[0] + sum; 22 } 23 }
在17行的循环,需要判断i-1个孩子当前获得的糖果数目是否真的比第i个孩子的少,如果真的少,才需要+1.例如:
ratings = {4,2,3,4,1}的时候,第一遍遍历得到的count数组是{1,1,2,3,1},此时从后往前遍历的时候ratings[3] > ratings[4],但是count[3]已经大于count[4]了,所以不需要更新count[3] = count[4]+1。
分类:
leetcode刷题总结
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了