[Leetcode] 135. Candy
2017-05-12 21:19
337 查看
题目:
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
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
相关文章推荐
- LeetCode 135. Candy
- 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 解题报告
- (Java) LeetCode 135. Candy —— 分发糖果
- LeetCode-135. Candy (JAVA)根据等级分糖果
- [LeetCode] 135. Candy
- Leetcode 135. Candy
- leetcode 135. Candy
- 【leetcode】135. Candy【java】
- Leetcode 135. Candy
- LeetCode力扣之135. Candy
- leetcode 135. Candy