Leetcode Candy
来源:互联网 发布:环刀法压实度软件 编辑:程序博客网 时间:2024/06/14 01:29
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?
因为至少有一个糖果,初始时将candy数组赋值为1.因为高rating的children要比neighbors获得更多的糖果。所以先进行一次遍历,高rating的children的糖果数比前一个children 多1.但这样处理完,还存在一种不符合情况的没有处理。前一个children的糖果数为1,而后一个rating更低的children糖果数也为1,这样是不符合题目要求的。因此从尾到头开始遍历,如果前一个children的rating大于后一个children,则设置其糖果数为max(candy[i],candy[i+1]) ,这样就修正了该情况,同时也会因为该修改而修改其他children的糖果数,从而符合题目要求。
代码如下:
class Solution {public: int candy(vector<int>& ratings) { int num = ratings.size(); int candy[num],total=0;; for(int i=0;i<num;i++) candy[i] = 1; for(int i=1;i<num;i++) { if(ratings[i] > ratings[i-1]) candy[i] = candy[i-1]+1; } total = candy[num-1]; for(int i=num-2;i>=0;i--) { if(ratings[i] > ratings[i+1]) { candy[i] = max(candy[i],candy[i+1]+1); } total += candy[i]; } return total; }};
阅读全文
0 0
- Leetcode: Candy
- LeetCode:Candy
- [leetcode]Candy
- Leetcode: Candy
- 【leetcode】Candy
- LeetCode:Candy
- [LeetCode] Candy
- [LeetCode]Candy
- [LeetCode] Candy
- 【LeetCode】Candy
- LeetCode | Candy
- Leetcode: Candy
- Candy - LeetCode
- leetcode Candy
- LeetCode Candy
- candy leetcode
- Candy -- LeetCode
- [LeetCode] Candy
- 查看linux发行版本及字长
- 关于while true 循环中 try catch块的使用
- react-native 导航栏的传值、tabbarNavigation 如何隐藏tabbar
- 关于Boolean==Boolean和Boolean=Boolean的启示
- canal 数据行解析错误
- Leetcode Candy
- 保持屏幕唤醒方法
- Android Wi-Fi Ethernet新IP获取机制—IpManager(Android 7.0)
- Android实战开发:获得屏幕物理尺寸、密度及分辨率
- Python range和xrange的区别
- php中FILES的注意点
- 多线程
- JavaScript中的小技巧和注意点(一)
- Android自定义控件:做一个拼图游戏