LeetCode 每日一题1052. 爱生气的书店老板

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.

提示:

  • 1 <= X <= customers.length == grumpy.length <= 20000
  • 0 <= customers[i] <= 1000
  • 0 <= grumpy[i] <= 1

方法一:滑动窗口

解题思路

理解题意后就很 easy 啦

  • 把满意数量分为 normalskillnomal 表示不使用技能获得的;skill 表示使用技能获得的。
  • 遍历数组累加 grumpy[i] == 0 时对应的 customers[i],求出 normal。(为了方便计算技能得分,累加后把 customers[i] = 0)。
  • 再次遍历数组求出 X 区间内最高的技能得分 skill
  • 返回 nomal + skill

参考代码

public int maxSatisfied(int[] customers, int[] grumpy, int X) {
    
    
    int n = customers.length;
    int normal = 0;
    for (int i = 0; i < n; i++) {
    
    
        if (grumpy[i] == 0) {
    
    
            normal += customers[i];
            customers[i] = 0;
        }
    }
    int skill = 0, temp= 0;
    for (int i = 0; i < n; i++) {
    
    
        temp += customers[i];
        if (i >= X) {
    
    
            temp -= customers[i - X];
        }
        skill = Math.max(skill, temp);
    }
    return normal + skill;
}

执行结果
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_27007509/article/details/113973580