【题解】力扣1052. 爱生气的书店老板
1052. 爱生气的书店老板
题目来源
思路
方法一
滑动窗口
- 先遍历一遍,统计老板不生气的时候的顾客总数。并且将当时的顾客数归为0
- 常规滑动窗口,窗口大小为\(X\),维护窗口内数值的最大值。
代码
class Solution {
public int maxSatisfied(int[] customers, int[] grumpy, int X) {
int len = customers.length;
int sum = 0;
for(int i = 0;i<len;i++){
if(grumpy[i] == 0){
sum += customers[i];
customers[i] = 0; // 将不生气的顾客数量变为0
}
}
int left = 0, right = 0;
int cnt = 0;
int max = 0;
while(right<len){
cnt+=customers[right];
if(right - left + 1 > X){ // 窗口大小大于限制
cnt -= customers[left];
left++;
}
max = Math.max(max, cnt); // 更新窗口内数值的最大值
right++;
}
return sum + max;
}
}