有一个书店老板,他的书店开了 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
方法一:滑动窗口
定义
class Solution:
def maxSatisfied(
self, customers: List[int], grumpy: List[int], minutes: int
) -> int:
s = sum(a * b for a, b in zip(customers, grumpy))
cs = sum(customers)
t = ans = 0
for i, (a, b) in enumerate(zip(customers, grumpy), 1):
t += a * b
if (j := i - minutes) >= 0:
ans = max(ans, cs - (s - t))
t -= customers[j] * grumpy[j]
return ans
class Solution {
public int maxSatisfied(int[] customers, int[] grumpy, int minutes) {
int s = 0, cs = 0;
int n = customers.length;
for (int i = 0; i < n; ++i) {
s += customers[i] * grumpy[i];
cs += customers[i];
}
int t = 0, ans = 0;
for (int i = 0; i < n; ++i) {
t += customers[i] * grumpy[i];
int j = i - minutes + 1;
if (j >= 0) {
ans = Math.max(ans, cs - (s - t));
t -= customers[j] * grumpy[j];
}
}
return ans;
}
}
class Solution {
public:
int maxSatisfied(vector<int>& customers, vector<int>& grumpy, int minutes) {
int s = 0, cs = 0;
int n = customers.size();
for (int i = 0; i < n; ++i) {
s += customers[i] * grumpy[i];
cs += customers[i];
}
int t = 0, ans = 0;
for (int i = 0; i < n; ++i) {
t += customers[i] * grumpy[i];
int j = i - minutes + 1;
if (j >= 0) {
ans = max(ans, cs - (s - t));
t -= customers[j] * grumpy[j];
}
}
return ans;
}
};
func maxSatisfied(customers []int, grumpy []int, minutes int) int {
s, cs := 0, 0
for i, c := range customers {
s += c * grumpy[i]
cs += c
}
t, ans := 0, 0
for i, c := range customers {
t += c * grumpy[i]
j := i - minutes + 1
if j >= 0 {
ans = max(ans, cs-(s-t))
t -= customers[j] * grumpy[j]
}
}
return ans
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
impl Solution {
pub fn max_satisfied(customers: Vec<i32>, grumpy: Vec<i32>, minutes: i32) -> i32 {
let k = minutes as usize;
let n = customers.len();
let mut sum = 0;
for i in 0..k {
if grumpy[i] == 1 {
sum += customers[i];
}
}
let mut max = sum;
for i in k..n {
if grumpy[i - k] == 1 {
sum -= customers[i - k];
}
if grumpy[i] == 1 {
sum += customers[i];
}
max = max.max(sum);
}
sum = 0;
for i in 0..n {
if grumpy[i] == 0 {
sum += customers[i];
}
}
sum + max
}
}