#medium #滑动窗口
有一个书店老板,他的书店开了 n
分钟。每分钟都有一些顾客进入这家商店。给定一个长度为 n
的整数数组 customers
,其中 customers[i]
是在第 i
分钟开始时进入商店的顾客数量,所有这些顾客在第 i
分钟结束后离开。
在某些时候,书店老板会生气。 如果书店老板在第 i
分钟生气,那么 grumpy[i] = 1
,否则 grumpy[i] = 0
。
当书店老板生气时,那一分钟的顾客就会不满意,若老板不生气则顾客是满意的。
书店老板知道一个秘密技巧,能抑制自己的情绪,可以让自己连续 minutes
分钟不生气,但却只能使用一次。
请你返回 这一天营业下来,最多有多少客户能够感到满意 。
提示:
n == customers.length == grumpy.length
1 <= minutes <= n <= 2 * 104
0 <= customers[i] <= 1000
grumpy[i] == 0 or 1
思路
所有不生气时间内的顾客总数:使用 $i$ 遍历 $[0, customers. Length)$,累加 $grumpy[i]==0$ 时的 $customers[i]$。
在窗口 $X$ 内因为生气而被赶走的顾客数:使用大小为 $X$ 的滑动窗口,计算滑动窗口内的 $grumpy[i]==1$ 时的 $customers[i]$,得到在滑动窗口内老板生气时对应的顾客数。
int maxSatisfied(int *customers, int customersSize, int *grumpy, int grumpySize, int minutes)
{
int res = 0;
for (int i = 0; i < customersSize; i++)
{
if (grumpy[i] == 0)
res += customers[i];
}
int max = 0;
for (int i = 0; i < minutes; i++)
{
if (grumpy[i] == 1)
max += customers[i];
}
int now = max;
for (int i = minutes; i < customersSize; i++)
{
if (grumpy[i] == 1)
now += customers[i];
if (grumpy[i - minutes] == 1)
now -= customers[i - minutes];
max = now > max ? now : max;
}
return res + max;
}