135. Candy

Ref: https://leetcode-cn.com/problems/candy/

这道题对糖果的分配规则属于局部最优,因此考虑贪心算法。由于仅需比较相邻孩子的评分大小,故考虑左规则left和右规则right分别正序和反序遍历数组,具体如下:

  • 左规则:从左向右遍历数组,如果ratings[i] > ratings[i - 1],则left[i] = left[i-1] + 1
  • 右规则:从右向左,如果ratings[i] > ratings[i + 1],则right[i] = right[i + 1] + 1
    最后,遍历left和right,累加max(left[i], right[i])得到最终结果。算法代码如下:
class Solution:
    def candy(self, ratings: List[int]) -> int:
        l = len(ratings)
        if l == 0:
            return 0
        left = [1 for _ in range(l)]
        right = left[:]
        count = 1
        for i in range(1, l):
            if ratings[i] > ratings[i - 1]:
                left[i] = left[i - 1] + 1
            count = left[-1]       
        for i in range(l - 2, -1, -1):
            if ratings[i] > ratings[i + 1]:
                right[i] = right[i + 1] + 1
            count += max(left[i], right[i])        
        return count
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 问题分析 There are N children standing in a line. Each child ...
    codingXue阅读 1,301评论 0 0
  • There are N children standing in a line. Each child is as...
    Jeanz阅读 1,256评论 0 0
  • 剑指offer 剑指 Offer 15. 二进制中1的个数[https://leetcode-cn.com/pro...
    scuwen阅读 1,499评论 0 0
  • There are N children standing in a line. Each child is as...
    ShutLove阅读 3,012评论 0 0
  • 题目 (https://leetcode-cn.com/problems/candy/)老师想给孩子们分发糖果,有...
    Mastergad阅读 2,405评论 0 0

友情链接更多精彩内容