[LeetCode] Candy
来源:互联网 发布:高丝婴儿面膜知乎 编辑:程序博客网 时间:2024/05/16 16:01
问题:
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?
分析:
两次遍历:
0. 所有的小朋友都分配一个糖果;
1. 从左向右:这次遍历的目的是处理所有的ascending subsequences。对于i和i+1,如果rating[i] < rating[i+1],那么后面的那一个的糖果一定要比前面的那个人多一个;
2. 从右向左:这次便利的目的是处理所有的descending subsequences。对于i和i - 1,如果input[i-1] > input[i]并且i-1的糖果还不比i的糖果多的话,那么首先他们的糖果一定一样多,所以也只要把i-1的糖果加1即可。
代码:(O(n))
class Solution {public:int candy(vector<int> &ratings) {vector<int> candy(ratings.size(), 1);for (int i = 1; i < ratings.size(); i ++) {if (ratings[i] > ratings[i - 1])candy[i] = candy[i - 1] + 1;}for (int i = ratings.size() - 2; i >= 0; i --) {if (ratings[i] > ratings[i + 1] && candy[i] <= candy[i+1])candy[i] = candy[i + 1] + 1;}int result = 0;for (int i = 0; i < candy.size(); i ++)result += candy[i];return result;}};
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 c编程一站式学习笔记(01), switch语句
- 第一个PSpice程序
- fwnx 递归范式
- FWNX - two kinds of Yourself
- 解决方案中如何添加项目
- [LeetCode] Candy
- Linux c编程一站式学习笔记(02), Return语句
- Ruby命令行参数介绍
- [LeetCode] Unique Binary Search Trees
- DP34 流水线调度问题 Assembly Line Scheduling @geeksforgeeks
- fwnx - 4.7 tree contains ; recursive
- Ch1-5: Write a method to replace all spaces in a string with ‘%20’.
- fwnx- find the common ancestor in a tree
- [LeetCode] Spiral Matrix