题目来源:LeetCode: 135 Candy
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?
- 规则1:每个人手中至少一个
- 规则2:评分更高的孩子比左右邻居糖果数量多:分别遍历比较比左侧孩子多,比右侧孩子多。
- 贪婪算法(Greedy Algorithm),从左到右遍历确保高分孩子比左侧糖果多,从右向左遍历确保高分孩子比右侧糖果多。
算法步骤
- 每个孩子一个糖果
- 从左到右遍历,ratings[i+1]>ratings[i]时,candies[i+1]=candies[i] +1
- 从右到左遍历,ratings[i-1]>ratings[i]时, candies[i-1]=max(candies[i-1], candies[i]+1)
源码
1 | int candy(int* ratings, int ratingsSize) { |
运行结果:
28 / 28 test cases passed.
Status: Accepted
Runtime: 16 ms
Submitted: 0 minutes agoYou are here! Your runtime beats 20% of csubmissions.
总结
- 贪婪算法模拟现实世界操作中一种可行方案
- 该问题中多次顺序遍历,但时间复杂度认为O(n)
- 注意边界情况的处理