LeetCode1052-爱生气的书店老板

题目链接

英文链接:https://leetcode.com/problems/grumpy-bookstore-owner/

中文链接:https://leetcode-cn.com/problems/grumpy-bookstore-owner/

题目详述

今天,书店老板有一家店打算试营业 customers.length 分钟。每分钟都有一些顾客(customers[i])会进入书店,所有这些顾客都会在那一分钟结束后离开。

在某些时候,书店老板会生气。 如果书店老板在第 i 分钟生气,那么 grumpy[i] = 1,否则 grumpy[i] = 0。 当书店老板生气时,那一分钟的顾客就会不满意,不生气则他们是满意的。

书店老板知道一个秘密技巧,能抑制自己的情绪,可以让自己连续 X 分钟不生气,但却只能使用一次。

请你返回这一天营业下来,最多有多少客户能够感到满意的数量。

示例:

1
2
3
4
5
输入: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

题目详解

  • 固定窗口大小的滑动窗口问题。
  • 为了避免相互干扰,创建两个变量 st,分别用来记录直接感到满意的顾客数量、老板抑制情绪感到满意的顾客数量。最终的结果就是 s + t
  • 遍历 customers,用变量 win 记录当前窗口老板抑制情绪感到满意的顾客数量,用 win 来更新 t
    • 如果 grumpy[i] == 0,那么 s += customers[i]
    • 如果 grumpy[i] == 1,那么 win += customers[i]
    • 维持窗口大小不超过 X,即如果 i >= X && grumpy[i - X] == 1,那么 win -= customers[i - X]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class LeetCode_01052 {

public int maxSatisfied(int[] customers, int[] grumpy, int X) {
int s = 0, t = 0;
for (int i = 0, win = 0; i < customers.length; ++i) {
if (grumpy[i] == 0) {
s += customers[i];
} else {
win += customers[i];
}
if (i >= X && grumpy[i - X] == 1) {
win -= customers[i - X];
}
t = Math.max(t, win);
}
return s + t;
}
}