LeetCode Algorithms 135. Candy 题解
来源:互联网 发布:c#图形编程 书籍 编辑:程序博客网 时间:2024/06/18 15:56
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?
题目意思是N个小孩一字排开,每个小孩有一个分数,分数比旁边的小孩高的要比旁边的小孩得到更多的糖果,每个小孩至少得到一个糖果,求最少需要多少糖果。
运用动态规划的思想,如果旁边的小孩分数比当前小孩要低,那么当前小孩的糖果数取当前小孩的糖果数和旁边小孩的糖果数+1的最大值,但是旁边的小孩有左右之分,为了减少一边的判断,先从左或者右开始初始化一次每个小孩的糖果数。
例如从队伍左开始初始化,判断左边小孩分数与当前小孩分数大小,如果当前小孩分数高,则当前小孩的糖果数是左边小孩糖果数+1,如此遍历一遍数组后,就能保证每个小孩的糖果数关系对于左边的小孩来说是正确的。
初始化之后可以使用简单的动态规划思想,从队伍右边开始判断,当前小孩的分数与右边小孩的分数,如果当前小孩分数较高,则取当前小孩的糖果数与右边小孩糖果数+1的最大值。这里要注意从右边开始判断,因为每次判断的是右边的分数较低者,要先确定小孩右边的糖果数最终是多少。
代码如下:
int Solution::candy(vector<int>& ratings) { int nums = ratings.size(); if (nums <= 1) return nums; vector<int> res(nums, 1); for (int i = 1; i < nums; i++) { if (ratings[i] > ratings[i - 1]) { res[i] = res[i - 1] + 1; } } for (int i = nums - 1; i > 0; i--) { if (ratings[i] < ratings[i - 1]) { res[i - 1] = max(res[i] + 1, res[i - 1]); } } int min_res = 0; for (int i = 0; i < nums; i++) { min_res += res[i]; } return min_res;}
- LeetCode Algorithms 135. Candy 题解
- leetcode题解-135. Candy
- LeetCode题解–135. Candy
- LeetCode题解:Candy
- LeetCode题解:Candy
- LeetCode 题解(89): Candy
- LeetCode 135:candy 题解 Python
- LeetCode Algorithms 78. Subsets 题解
- LeetCode Algorithms 2. Add Two Numbers 题解
- LeetCode Algorithms 279. Perfect Squares 题解
- LeetCode Algorithms 18. 4Sum 题解
- LeetCode Algorithms 292. Nim Game 题解
- LeetCode Algorithms 50. Pow(x, n) 题解
- LeetCode Algorithms 7. Reverse Integer 题解
- LeetCode Algorithms 113. Path Sum II 题解
- LeetCode Algorithms 5. Longest Palindromic Substring 题解
- LeetCode Algorithms 128. Longest Consecutive Sequence 题解
- LeetCode Algorithms 76. Minimum Window Substring 题解
- [java-算法-数据结构] 判断栈的弹出顺序是否正确
- Matlab emd工具箱、时频分析工具箱下载以及安装方法
- JS判断手机端和电脑端调转代码
- 单元测试
- [MFC] 入门级demo:基于MFC的五子棋程序
- LeetCode Algorithms 135. Candy 题解
- (转)JVM之用Java解析class文件
- AIDL在Android Studio中简单使用
- 4-5 求自定类型元素的最大值 (10分)
- 如何让远程的电脑识别U盘
- 产品经理之产品运营-全栈工程师熊盼
- Spring相关
- JFrame设置背景图片
- Android系统自带的常用数据库