题目链接:https://leetcode-cn.com/problems/grumpy-bookstore-owner/
定义三个变量:sat表示所有的顾客数,unsat表示老板不控制自己的时候会不满意的顾客数,mx表示老板连续X分钟不生气所能减少的最大不满意顾客数。
滑动窗口长度为X,左右向右遍历,每一步都用customers[i] * grumpy[i]计算出某一分钟不满意的顾客数,并取max,最后得到的就是mx
代码如下:
class Solution {
public:
int maxSatisfied(vector<int>& customers, vector<int>& grumpy, int X) {
int l = 0, r = X;
int mx = -1, pos = 0;
for(int i = l; i < r; i++) {
pos += customers[i] * grumpy[i];
}
mx = pos;
while(r < customers.size()) {
pos += customers[r] * grumpy[r];
pos -= customers[l] * grumpy[l];
r++;
l++;
mx = max(mx, pos);
}
int unsat = 0, sat = 0;
for(int i = 0; i < customers.size(); i++) {
unsat += customers[i] * grumpy[i];
sat += customers[i];
}
return sat - unsat + mx;
}
};