Leetcode

Leetcode 135. Candy

2021-08-04  本文已影响0人  SnailTyan

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Candy

2. Solution

解析:Version 1,首先保证糖果至少为1,因此创建值都为1的数组,然后从从左往右,右边评分大于左侧评分时,右侧糖果等于左侧糖果加1,保证了糖果从左到右的分配关系,接下来,从右向左,左侧评分大于右侧评分时,左侧糖果等于右侧糖果加1,保证了糖果从右到左的分配关系,这样就保证了糖果的公正分配,每次加1,保证了通过最少的糖果来保证分配关系,最终数组求和就可得出所需的糖果数量。

class Solution:
    def candy(self, ratings: List[int]) -> int:
        n = len(ratings)
        candies = [1] * n
        for i in range(1, n):
            if ratings[i] > ratings[i-1] and candies[i] <= candies[i-1]:
                candies[i] = candies[i-1] + 1
        for i in range(n-1, 0, -1):
            if ratings[i] < ratings[i-1] and candies[i] >= candies[i-1]:
                candies[i-1] = candies[i] + 1
        return sum(candies)

Reference

  1. https://leetcode.com/problems/candy/
上一篇下一篇

猜你喜欢

热点阅读