程序员的资源宝库

网站首页 > gitee 正文

爱生气的书店老板 爱生气的小老鼠绘本

sanyeah 2024-03-29 17:58:12 gitee 9 ℃ 0 评论

1.题目

今天,书店老板有一家店打算试营业 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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/grumpy-bookstore-owner
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

2.解题思路(自己和官方解法一样,只是自己代码不够简洁)

我们转换一下我们要找的东西,我们要求最多地客户能够感到满意,那么我们就需要让老板把控制情绪的这个能力发挥到最大,也就是求X区间内老板心情不好的时候进入书店的游客总数最大,即我们把X区间内所有grumpy为1的值的下标对应的customers的值加起来最大,我们就可以让感到满意的顾客数量最大。

长度是不变的,我们可以采用滑动窗口的解法来做,记录这个窗口里面老板心情为1的所有值的大小,统计出最大的数量,我个人的解法是记录了老板什么时候开始抑制心情,然后在重新求sum。官方解法是先求出老板心情好的游客的总数,然后再统计出区间X内最大的可抑制的游客数目,加起来就是我们需要的答案。

3.滑动窗口解法(自己)

class Solution {
public:
    int maxSatisfied(vector<int>& customers, vector<int>& grumpy, int X) {
    	int place = 0;//开始抑制自己情绪地位置
    	int max = 0;
    	int sum = 0;
    	int left = 0, right = left + X;
    	for(int i = left; i < right; i++) {
    		if(grumpy[i])
    			sum += customers[i];
    	}
    	max = sum;
    	while(right < customers.size()) {
    		if(grumpy[left])
    			sum -= customers[left];
    		left++;
    		if(grumpy[right])
    			sum += customers[right];
    		right++;
    		if(sum > max) {
    			max =sum;
    			place = left;
    		}
    	}
    	sum = 0;
    	for(int i = 0; i < customers.size(); i++) {
    		if(i >= place && i < place + X) {
    			sum += customers[i];
    		}
    		else {
    			if(grumpy[i] == 0)
    				sum += customers[i];
    		}
    	}
    	return sum;
    }
};

4.滑动窗口解法(官方)

class Solution {
public:
    int maxSatisfied(vector<int>& customers, vector<int>& grumpy, int X) {
        int total = 0;
        int n = customers.size();
        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 += customers[i] * grumpy[i];
        }
        int maxIncrease = increase;
        for (int i = X; i < n; i++) {
            increase = increase - customers[i - X] * grumpy[i - X] + customers[i] * grumpy[i];
            maxIncrease = max(maxIncrease, increase);
        }
        return total + maxIncrease;
    }
};

作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/grumpy-bookstore-owner/solution/ai-sheng-qi-de-shu-dian-lao-ban-by-leetc-dloq/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表