今天,书店老板有一家店打算试营业 customers.length 分钟。每分钟都有一些顾客(customers[i])会进入书店,全部这些顾客都会在那一分钟结束后离开。c++
在某些时候,书店老板会生气。 若是书店老板在第 i 分钟生气,那么 grumpy[i] = 1,不然 grumpy[i] = 0。 当书店老板生气时,那一分钟的顾客就会不满意,不生气则他们是满意的。网络
书店老板知道一个秘密技巧,能抑制本身的情绪,可让本身连续 X 分钟不生气,但却只能使用一次。code
请你返回这一天营业下来,最多有多少客户可以感到满意的数量。leetcode
示例:get
输入: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.io
提示:class
1 <= X <= customers.length == grumpy.length <= 20000
0 <= customers[i] <= 1000
0 <= grumpy[i] <= 1技巧
来源:力扣(LeetCode)
连接:https://leetcode-cn.com/problems/grumpy-bookstore-owner
著做权归领扣网络全部。商业转载请联系官方受权,非商业转载请注明出处。统计
咱们转换一下咱们要找的东西,咱们要求最多地客户可以感到满意,那么咱们就须要让老板把控制情绪的这个能力发挥到最大,也就是求X区间内老板心情很差的时候进入书店的游客总数最大,即咱们把X区间内全部grumpy为1的值的下标对应的customers的值加起来最大,咱们就可让感到满意的顾客数量最大。di
长度是不变的,咱们能够采用滑动窗口的解法来作,记录这个窗口里面老板心情为1的全部值的大小,统计出最大的数量,我我的的解法是记录了老板何时开始抑制心情,而后在从新求sum。官方解法是先求出老板心情好的游客的总数,而后再统计出区间X内最大的可抑制的游客数目,加起来就是咱们须要的答案。
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; } };
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) 著做权归做者全部。商业转载请联系做者得到受权,非商业转载请注明出处。