Leetcode 1052. 爱生气的书店老板 题解

题目链接: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;
    }
};

版权声明:本文为weixin_42396397原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。