算法题--给小朋友发糖问题

image.png

0. 链接

题目链接

1. 题目

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?

Example 1:

Input: [1,0,2]
Output: 5
Explanation: You can allocate to the first, second and third child with 2, 1, 2 candies respectively.

Example 2:

Input: [1,2,2]
Output: 4
Explanation: You can allocate to the first, second and third child with 1, 2, 1 candies respectively.
             The third child gets 1 candy because it satisfies the above two conditions.

2. 思路1: 双向加成法

  1. 基本思路是:
  • 首先初始化一个candies数组, 表示每个小孩分到的糖数, 初始为1
  • 先自i=1开始从左到右遍历ratings数组, 当遇到ratings[i] > ratings[i - 1],即遇到一个分数比左边邻居高的小朋友时, 则 将他的糖数变为max(candies[i], candies[i - 1] + 1), 确保他的糖比左边小朋友多
  • 再从i = n - 2开始从右到左遍历ratings数组, 当遇到ratings[i] > ratings[i + 1]时, 即遇到一个分数比右边邻居高的小朋友时, 则将他的糖数变为max(candies[i], candies[i + 1] + 1), 确保他的糖同时也比右边的邻居多
  1. 分析:
  • 对于每个节点, 都要遍历2遍 因此时间复杂度为O(n), 空间复杂度为O(n)
  1. 复杂度
  • 时间复杂度 O(n)
  • 空间复杂度 O(n)

3. 代码

# coding:utf8
from typing import List


class Solution:
    def candy(self, ratings: List[int]) -> int:
        n = len(ratings)
        if n == 0:
            return 0

        candies = [1] * n
        for i in range(1, n):
            if ratings[i] > ratings[i - 1]:
                new_num = max(candies[i], candies[i - 1] + 1)
                candies[i] = new_num
        for i in range(n - 2, -1, -1):
            if ratings[i] > ratings[i + 1]:
                new_num = max(candies[i], candies[i + 1] + 1)
                candies[i] = new_num

        return sum(candies)


def my_test(solution, ratings):
    print('input: ratings={}; output: {}'.format(ratings, solution.candy(ratings)))


solution = Solution()

my_test(solution, [1, 0, 2])
my_test(solution, [1, 2, 2])
my_test(solution, [2, 2, 3, 1, 0, 1, 0, 3, 2, 1, 0])

输出结果

input: ratings=[1, 0, 2]; output: 5
input: ratings=[1, 2, 2]; output: 4
input: ratings=[2, 2, 3, 1, 0, 1, 0, 3, 2, 1, 0]; output: 21

4. 结果

image.png

5. 思路2: 曲线法

  1. 过程
  • 增加up, down, peak, 从左到右只遍历1次
  • up表示当前ratings连续上升的步数, down表示当前ratings连续下降的步数, peak表示最近的1次连续上升阶段的步数
  • 关于发糖的问题,可以换个角度来看待,即如果将ratings值随下标的变化,看做一个曲线的话,这个曲线可以看成是若干个连续上升的上坡、若干个平坡、若干个下坡构成;
  • 当处于上坡阶段时,我们给第一步的小孩先发1颗糖, 轮到给第二个小朋友发的时候,就不能只发1颗糖了,因为他比第一个小朋友rating高, 所以给他发2颗糖,依次类推,给第up个小朋友,就发up颗糖, 顺便更新下peak,表示连续up的步数
  • 当处于平坡的时候,意味着只需要给小孩发1颗糖就好了,因为他没有超过他左边邻居的rating值嘛, 另外peak也重置为1
  • 当处于下坡的时候,此时第一个处于下坡的小孩,要发的糖数要分情况对待,
    • down < peak时,即当前是从一个峰值直接转而下跌,则只需要给这个小孩发1颗糖,同时递增down;同理,当遇到下坡第2个小孩的时候,给他发1颗糖的同时,要给第1个小孩再补一颗糖,这一步要发出去2颗糖;遇到下坡第3个小孩的时候,给他发1颗糖的同时,要给前2个小孩各多发1颗糖,这次发出去3颗糖;可以看出在下坡第down步的时候,发出去down颗糖
    • down >= peak时, 表示当前已经下坡太多步了,此时下坡处第1个小孩的数量,已经赶上了峰值处小孩的糖数量,为了保持峰值小孩的糖数量处于优势,从当前到以后每下坡1步,都要额外给峰值小孩补1颗糖,所以每步发出去down + 1颗糖
  • 将汇总的发糖数candies返回即可
  1. 分析
    利用此法, 在两个指针startend的帮助下,每个节点只被遍历1次,就得出了结论,时间复杂度降低到了O(n), 空间复杂度仍然是O(1)
  2. 时间复杂度 O(n)
  3. 空间复杂度 O(1)

6. 代码

# coding:utf8
from typing import List


class Solution:
    def candy(self, ratings: List[int]) -> int:
        n = len(ratings)
        if n <= 1:
            return n

        up = 1
        peak = up
        down = 0
        candies = 1
        for i in range(1, len(ratings)):
            if ratings[i] > ratings[i - 1]:
                up += 1
                peak = up
                down = 0
                candies += up
            elif ratings[i] < ratings[i - 1]:
                up = 1
                down += 1
                candies += down if down < peak else down + 1
            else:
                up = 1
                down = 0
                peak = up
                candies += 1

        return candies


def my_test(solution, ratings):
    print('input: ratings={}; output: {}'.format(ratings, solution.candy(ratings)))


solution = Solution()

my_test(solution, [1, 0, 2])
my_test(solution, [1, 2, 2])
my_test(solution, [2, 2, 3, 1, 0, 1, 0, 3, 2, 1, 0])

输出结果

input: ratings=[1, 0, 2]; output: 5
input: ratings=[1, 2, 2]; output: 4
input: ratings=[2, 2, 3, 1, 0, 1, 0, 3, 2, 1, 0]; output: 21

7. 结果

image.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 218,204评论 6 506
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,091评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,548评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,657评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,689评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,554评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,302评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,216评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,661评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,851评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,977评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,697评论 5 347
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,306评论 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,898评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,019评论 1 270
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,138评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,927评论 2 355