美文网首页Leetcode
Leetcode 135. Candy

Leetcode 135. Candy

作者: SnailTyan | 来源:发表于2021-08-04 10:26 被阅读0次

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

1. Description

Candy

2. Solution

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

  • Version 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/

相关文章

  • 经典算法题:分发糖果

    135. 分发糖果[https://leetcode.cn/problems/candy/] 难度:困难 n 个孩...

  • 135. Candy [Hard] DP

    135. Candy

  • Leetcode 135. Candy

    There are N children standing in a line. Each child is as...

  • Leetcode 135. Candy

    文章作者:Tyan博客:noahsnail.com[http://noahsnail.com] | CSDN[ht...

  • [LeetCode] 135. Candy (hard)

    原题 思路:前后两遍遍历

  • 135. Candy

    题目 思路 dp[i]:记录i的获取糖果树 从左向右扫描,保证一个方向上分数更大的糖果更多 从右向左扫描,保证另一...

  • 135. Candy

    题目分析 There are N children standing in a line. Each child ...

  • 135. Candy

    There are N children standing in a line. Each child is as...

  • 135. Candy

    题目描述:N个孩子坐在一排,每个孩子分配一个等级值,按如下要求给每个孩子分糖: 每个孩子至少有一个 等级高的孩子比...

  • 135. Candy

    There are N children standing in a line. Each child is as...

网友评论

    本文标题:Leetcode 135. Candy

    本文链接:https://www.haomeiwen.com/subject/sfuomltx.html