[Leetcode] 135. Candy
来源:互联网 发布:电商系统源码下载 编辑:程序博客网 时间:2024/06/18 09:40
题目:
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?
思路: 扫描两遍数列,第一遍保证与左邻居有序,第二遍保证与右邻居有序。 时间复杂度O(N)
代码:
class Solution(object): def candy(self, ratings): if len(ratings) == 0: return 0 candy = [0 for i in range(0,len(ratings))] candy[0] = 1 for i in range(1,len(ratings)): if ratings[i] > ratings[i-1]: candy[i] = candy[i-1]+1 else: candy[i] = 1 ans = candy[len(ratings)-1] for i in range(len(ratings)-2,-1,-1): if ratings[i] > ratings[i+1] and candy[i] <= candy[i+1]: candy[i] = candy[i+1]+1 ans += candy[i] return ans
0 0
- [LeetCode]135.Candy
- 135. Candy Leetcode Python
- [Leetcode] 135. Candy
- [leetcode] 135.Candy
- [leetcode] 135. Candy
- leetcode 135. Candy
- leetcode 135. Candy
- [LeetCode]135. Candy
- LeetCode 135. Candy
- Leetcode 135. Candy
- leetcode.135. Candy
- LeetCode 135. Candy
- [leetcode] 【数组】 135. Candy
- LeetCode-135.Candy
- LeetCode 135. Candy
- Leetcode 135. Candy
- leetcode-135. Candy
- [LeetCode] 135. Candy
- java XML转JSON格式
- flex 最后一行左对齐
- 线程 中断 Thread.interrupt()使用
- HTML5学习笔记 —— JavaScript语句
- 如何优化MySQL
- [Leetcode] 135. Candy
- 微信小程序获取用户openid
- grep
- Ajax数据格式—HTML
- 袁萌乘坐波音737的惊魂一刻
- Java环境变量配置
- 欢迎使用CSDN-markdown编辑器
- UnityVR.07 VRTK快速入门学习手册(一)
- 汇编程序:多数绝对值和