【每日一题】爱生气的书店老板

1052. 爱生气的书店老板

有一个书店老板,他的书店开了 n 分钟。每分钟都有一些顾客进入这家商店。给定一个长度为 n 的整数数组 customers ,其中 customers[i] 是在第 i 分钟开始时进入商店的顾客数量,所有这些顾客在第 i 分钟结束后离开。

在某些时候,书店老板会生气。 如果书店老板在第 i 分钟生气,那么 grumpy[i] = 1,否则 grumpy[i] = 0

当书店老板生气时,那一分钟的顾客就会不满意,若老板不生气则顾客是满意的。

书店老板知道一个秘密技巧,能抑制自己的情绪,可以让自己连续 minutes 分钟不生气,但却只能使用一次。

请你返回 这一天营业下来,最多有多少客户能够感到满意

示例 1:

输入:customers = [1,0,1,2,1,1,7,5], grumpy = [0,1,0,1,0,1,0,1], minutes = 3
输出:16
解释:书店老板在最后 3 分钟保持冷静。
感到满意的最大客户数量 = 1 + 1 + 1 + 1 + 7 + 5 = 16.

示例 2:

输入:customers = [1], grumpy = [0], minutes = 1
输出:1

提示:

  • n == customers.length == grumpy.length
  • 1 <= minutes <= n <= 2 * 104
  • 0 <= customers[i] <= 1000
  • grumpy[i] == 0 or 1

这题用滑动窗口来做。思路如下:

  1. 首先,计算出老板不使用秘密技巧时,所有顾客满意的数量。

  2. 接下来,使用一个长度为 minutes 的滑动窗口,计算每个窗口内老板使用秘密技巧后可以使顾客满意的数量增加多少。具体步骤如下:

    • 初始化窗口,计算第一个窗口内老板使用秘密技巧后可以使顾客满意的数量增加多少。
    • 从第二个窗口开始,每次滑动窗口时,计算新窗口内老板使用秘密技巧后可以使顾客满意的数量增加多少。同时,需要减去上一个窗口的第一个分钟的满意顾客数量(如果老板在这个时间段使用秘密技巧的话)。
  3. 返回最大的满意顾客数量。

class Solution(object):
    def maxSatisfied(self, customers, grumpy, minutes):
        """
        :type customers: List[int]
        :type grumpy: List[int]
        :type minutes: int
        :rtype: int
        """
        n = len(customers)
        total_satisfy = sum(customers[i] for i in range(n) if grumpy[i] == 0)
        current_increase = 0
        
        # 从第一个窗口计算能增加多少满意人数
        for i in range(minutes):
            if grumpy[i] == 1:
                current_increase += customers[i]
        
        # 长为minutes的滑动窗口
        max_increase = current_increase
        for i in range(minutes, n):
            if grumpy[i] == 1:
                current_increase += customers[i]
            if grumpy[i - minutes] == 1:
                current_increase -= customers[i - minutes]
            max_increase = max(max_increase, current_increase)
        
        return total_satisfy + max_increase

我自己写的题解是这样的,没有上面那个简洁,也放一下:

class Solution(object):
    def maxSatisfied(self, customers, grumpy, minutes):
        """
        :type customers: List[int]
        :type grumpy: List[int]
        :type minutes: int
        :rtype: int
        """
        happy = [1 - x for x in grumpy] # 不生气为1,生气为0
        total_satisfiy = sum(x * y for x, y in zip(customers, happy)) # 总满意人数
        # 初始化一个长为minutes的滑动窗口
        start = 0
        end = minutes
        # 从第一个窗口计算能增加多少满意人数
        for i in range(start, end):
            if happy[i] == 0:
                total_satisfiy += customers[i]
        max_satisfiy = total_satisfiy
        # 滑动窗口
        while end < len(customers):
            if happy[start] == 0:
                total_satisfiy -= customers[start]
            if happy[end] == 0:
                total_satisfiy += customers[end]
            if max_satisfiy < total_satisfiy:
                max_satisfiy = total_satisfiy
            start += 1
            end += 1
        
        return max_satisfiy

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章