贪心算法分发糖果python
时间: 2024-01-11 18:22:14 浏览: 100
贪心算法python实现
以下是使用贪心算法分发糖果的Python示例:
```python
def candy(ratings):
n = len(ratings)
candies = [1] * n
# 从左到右遍历,保证右边评分高的孩子获得更多糖果
for i in range(1, n):
if ratings[i] > ratings[i-1]:
candies[i] = candies[i-1] + 1
# 从右到左遍历,保证左边评分高的孩子获得更多糖果
for i in range(n-2, -1, -1):
if ratings[i] > ratings[i+1]:
candies[i] = max(candies[i], candies[i+1] + 1)
return sum(candies)
ratings = [1, 0, 2]
print(candy(ratings)) # 输出:5
```
阅读全文