package com.heu.wsq.leetcode.slidingwindow;
/**
* 1052. 爱生气的书店老板
* @author wsq
* @date 2021/2/23
* 今天,书店老板有一家店打算试营业 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.
*
* 链接:https://leetcode-cn.com/problems/grumpy-bookstore-owner
*/
public class MaxSatisfied {
/**
* 我的笨方法,在窗口内数组求和的过程中,每次都进行了窗口的扫描,影响算法性能,
* 这里我们可以使用滑动窗口的思想,窗口向右滑动,最左边的元素被移除,新增了最后端的元素,可以避免线性扫描求和
* @param customers
* @param grumpy
* @param X
* @return
*/
public int myMaxSatisfied(int[] customers, int[] grumpy, int X) {
int n = customers.length;
int customerNum = 0;
for(int i = 0; i < n; i++){
if(grumpy[i] == 0){
customerNum += customers[i];
}
}
int ans = customerNum;
for(int i = 0; i < n; i++){
int tmp = customerNum;
if(grumpy[i] == 1){
// tmp += grumpy[i];
for(int j = i; j < i + X && j < n; j++){
if(grumpy[j] == 1){
tmp += customers[j];
}
}
ans = Math.max(tmp, ans);
}
}
return ans;
}
/**
* 采用滑动窗口要进行性能优化,避免线性扫描求和
* @param customers
* @param grumpy
* @param X
* @return
*/
public int maxSatisfied(int[] customers, int[] grumpy, int X) {
int n = customers.length;
int total = 0;
for (int i = 0; i < n; i++){
if (grumpy[i] == 0){
total += customers[i];
}
}
int increase = 0;
for (int i = 0; i < X; i++){
increase += grumpy[i] * customers[i];
}
int maxIncrease = increase;
for (int i = X; i < n; i++){
increase = increase - grumpy[i - X] * customers[i - X] + grumpy[i] * customers[i];
maxIncrease = Math.max(increase, maxIncrease);
}
return total + maxIncrease;
}
}