[LeetCode] 1052. Grumpy Bookstore Owner
Today, the bookstore owner has a store open for customers.length minutes. Every minute, some number of customers (customers[i]) enter the store, and all those customers leave after the end of that minute.
On some minutes, the bookstore owner is grumpy. If the bookstore owner is grumpy on the i-th minute, grumpy[i] = 1, otherwise grumpy[i] = 0. When the bookstore owner is grumpy, the customers of that minute are not satisfied, otherwise they are satisfied.
The bookstore owner knows a secret technique to keep themselves not grumpy for X minutes straight, but can only use it once.
Return the maximum number of customers that can be satisfied throughout the day.
Example 1:
Input: customers = [1,0,1,2,1,1,7,5], grumpy = [0,1,0,1,0,1,0,1], X = 3
Output: 16
Explanation: The bookstore owner keeps themselves not grumpy for the last 3 minutes.
The maximum number of customers that can be satisfied = 1 + 1 + 1 + 1 + 7 + 5 = 16.
Note:
1 <= X <= customers.length == grumpy.length <= 20000
0 <= customers[i] <= 1000
0 <= grumpy[i] <= 1
爱生气的书店老板。
今天,书店老板有一家店打算试营业 customers.length 分钟。每分钟都有一些顾客(customers[i])会进入书店,所有这些顾客都会在那一分钟结束后离开。在某些时候,书店老板会生气。 如果书店老板在第 i 分钟生气,那么 grumpy[i] = 1,否则 grumpy[i] = 0。 当书店老板生气时,那一分钟的顾客就会不满意,不生气则他们是满意的。
书店老板知道一个秘密技巧,能抑制自己的情绪,可以让自己连续 X 分钟不生气,但却只能使用一次。
请你返回这一天营业下来,最多有多少客户能够感到满意的数量。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/grumpy-bookstore-owner
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路
思路是滑动窗口。这道题我提供两个做法,一个是固定长度的滑动窗口,一个是类似76题的那种模板。
可以用固定长度做是因为老板有一次机会可以让自己连续 X 分钟不生气。
复杂度
时间O(n)
空间O(1)
代码一 - 固定长度的滑动窗口
Java实现
class Solution {
public int maxSatisfied(int[] customers, int[] grumpy, int minutes) {
int n = customers.length;
int sum = 0;
int k = minutes;
// 如果前k分钟不生气的满意值
for (int i = 0; i < k; i++) {
sum += customers[i];
}
// 之后的分钟按是否生气正常累加客户的满意值
for (int i = k; i < n; i++) {
if (grumpy[i] == 0) {
sum += customers[i];
}
}
int res = sum;
for (int i = k; i < n; i++) {
if (grumpy[i] == 1) {
sum += customers[i];
}
if (grumpy[i - k] == 1) {
sum -= customers[i - k];
}
res = Math.max(res, sum);
}
return res;
}
}
代码二
Java实现
class Solution {
public int maxSatisfied(int[] customers, int[] grumpy, int minutes) {
int satisfied = 0;
int n = customers.length;
// 老板不生气的时段内顾客的满意度
for (int i = 0; i < n; i++) {
if (grumpy[i] == 0) {
satisfied += customers[i];
}
}
int start = 0;
int end = 0;
int curSum = 0;
int max = 0;
while (end < n) {
if (grumpy[end] == 1) {
curSum += customers[end];
}
end++;
// 如果长度正好等于minutes,统计当前max的值,代表能有多少顾客的满意度可以被改变
if (end - start == minutes) {
max = Math.max(max, curSum);
if (grumpy[start] == 1) {
curSum -= customers[start];
}
start++;
}
}
return satisfied + max;
}
}
相关题目
1052. Grumpy Bookstore Owner
1849. Grumpy Bookstore Owner