1052. 爱生气的书店老板
今天,书店老板有一家店打算试营业 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.
题解:
本题考查的是滑动窗口,其长度固定为X。
首先这种思想参考的是:这位大佬
我们需要查找这么一个长度为X的窗口:窗口内能留住更多的原本因为老板生气而被赶走的顾客。最终最多能满意的顾客数量=窗口内留住的顾客最大值+所有不生气时间的顾客。
public int maxSatisfied(int[] customers, int[] grumpy, int X) {
int n = customers.length;
int sum = 0; //不生气时间的顾客总数
for (int i = 0; i < n; i++) {
if (grumpy[i] == 0) {
sum += customers[i];
}
}
int curValue = 0; //当前窗口内不满意顾客的数量
for (int i = 0; i < X; i++) { //前K分钟不满意顾客数量
if (grumpy[i] == 1) {
curValue += customers[i];
}
}
int resValue = curValue;
for (int i = X; i < n; i++) { //开始滑动窗口
if (grumpy[i] == 1) { //新进入窗口的元素
curValue += customers[i];
}
if (grumpy[i - X] == 1) { //离开窗口的元素
curValue -= customers[i - X];
}
resValue = Math.max(resValue, curValue);
}
return sum + resValue;
}
还有另外一种思想:
首先求出[0,X-1]窗口内满意顾客的人数,开始向右滑动,进来一个新的,出去一个,求出满意顾客的数量,更新最大值。
public int maxSatisfied(int[] customers, int[] grumpy, int X) {
int ans = 0;
int sum = 0;
for (int i = 0; i < X; i++) { //开始窗口内顾客满意数量
sum += customers[i];
}
for (int i = X; i < customers.length; i++) { //开始窗口外顾客满意数量
sum += (grumpy[i] == 0) ? customers[i] : 0;
}
ans = sum;
for (int i = 1; i <= customers.length - X; i++) {
sum -= customers[i - 1] * grumpy[i - 1];
sum += customers[i - 1 + X] * grumpy[i - 1 + X];
ans = Math.max(ans, sum);
}
return ans;
}
网友评论