题目
今天,书店老板有一家店打算试营业 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
分析
customers = [1,0,1,2,1,1,7,5]
grumpy = [0,1,0,1,0,1,0,1]
grumpy 为0的时候,对应custormers 不生气,所以1+1+1+7 (sum)肯定不生气
grumpy 为1的时候,控制一个滑动窗口,窗口最大为3,而需要滑动的窗口为:[0,,0,,0,,0,] 这里0为肯定不生气,不需要填充因子X,而*则为对应customers的个数,所以题目转化为求[0,0,0,2,0,1,0,5] 在滑动窗口为3时候的最大值max。
将最大值max和sum相加,即为最多客户满意的数量
代码
int sum = 0;
for (int i = 0; i < customers.length; i++) {
if (grumpy[i] != 1)
sum += customers[i];
else
grumpy[i] = customers[i];
}
//满意
int save = 0;
for (int i = 0; i < X; i++) {
save += grumpy[i];
}
int max = save;
for (int i = X; i < customers.length; i++) {
save -= grumpy[i - X];
save += grumpy[i];
if (save > max)
max = save;
}
return sum + max;