题目

今天,书店老板有一家店打算试营业 customers.length 分钟。每分钟都有一些顾客(customers[i])会进入书店,所有这些顾客都会在那一分钟结束后离开。

在某些时候,书店老板会生气。 如果书店老板在第 i 分钟生气,那么 grumpy[i] = 1,否则 grumpy[i] = 0。 当书店老板生气时,那一分钟的顾客就会不满意,不生气则他们是满意的。

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

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

示例:

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

提示:

  • 1 <= X <= customers.length == grumpy.length <= 20000
  • 0 <= customers[i] <= 1000
  • 0 <= grumpy[i] <= 1

题解

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution:
def maxSatisfied(self, customers: List[int], grumpy: List[int], X: int) -> int:
# 两个数组,一个是每分钟客户数量,另一个是老板在该分钟是否生气
# 求最多有多少客户感到满意
# 老板能抑制情绪,连续x分钟不生气
# 连续x分钟可以看成滑动窗口求最大值

# 先计算本来不生气能得到的总收益,并把这些置0
gold_value = 0
for i in range(len(customers)):
if not grumpy[i]:
gold_value += customers[i]
customers[i]=0
left = 0
max_increase = 0
while left+X<=len(customers):
max_increase = max(max_increase,sum(customers[left:left+X]))
left+=1
return max_increase+gold_value