zoukankan      html  css  js  c++  java
  • 1052. Grumpy Bookstore Owner

    问题:

    给定一个每分钟来客数量的数组,和一个同一时刻店主是否松懈的数组,

    如果店主松懈:1,那么那一分钟的来客满意度为0,否则满意度=来客数量。

    店主有一技巧可使得,即使店主松懈,来客也能够满足X分钟。这一技巧只能用一次,

    求一段时间的最大满意度和。

    Example 1:
    Input: customers = [1,0,1,2,1,1,7,5], grumpy = [0,1,0,1,0,1,0,1], X = 3
    Output: 16
    Explanation: The bookstore owner keeps themselves not grumpy for the last 3 minutes. 
    The maximum number of customers that can be satisfied = 1 + 1 + 1 + 1 + 7 + 5 = 16.
    
    Note:
    1 <= X <= customers.length == grumpy.length <= 20000
    0 <= customers[i] <= 1000
    0 <= grumpy[i] <= 1
    

      

    解法:

    mask遮罩问题:

    没有技巧前的满意度总和,为固定值,即grumpy[i]==0的时候,来客数之和。grpsum

    而这个技巧的功能,只是在上述固定的满意度之上,追加了customers连续X元素子数组中grumpy[i]==1的的和。

    我们使用sumX来计算。

        这里对sumX,为滑动窗口(往后移一位+新的customers[i],-移出的customers[i-X]),固定长度X,且只计算grumpy[i]==1的时候。

    1             if(grumpy[i]==0){
    2                 grpsum+=customers[i];
    3             }else{
    4                 sumX+=customers[i];
    5             }
    6             if(i>=X && grumpy[i-X]!=0){
    7                 sumX-=customers[i-X];
    8             }
    9             res=max(res, sumX);

    我们只需要计算sumX的最大值,

    返回grpsum+grpsum的最大值即可。

    代码参考:

     1 class Solution {
     2 public:
     3     int maxSatisfied(vector<int>& customers, vector<int>& grumpy, int X) {
     4         int n=customers.size();
     5         int res=INT_MIN;
     6         int grpsum=0;
     7         int sumX=0;
     8         for(int i=0; i<n; i++){
     9             if(grumpy[i]==0){
    10                 grpsum+=customers[i];
    11             }else{
    12                 sumX+=customers[i];
    13             }
    14             if(i>=X && grumpy[i-X]!=0){
    15                 sumX-=customers[i-X];
    16             }
    17             res=max(res, sumX);
    18         }
    19         return res+grpsum;
    20     }
    21 };
  • 相关阅读:
    《Linux内核设计与实现》读书笔记 第十八章 调试
    《Linux内核设计与实现》读书笔记 第五章 系统调用
    [题解] LuoguP5488 差分与前缀和
    [题解] LuoguP4655 [CEOI2017]Building Bridges
    [题解] Tenka1 Programmer Contest 2019 E
    [题解] LuoguP4284 [SHOI2014]概率充电器
    长链剖分学习笔记
    [题解] LuoguP4292 [WC2010]重建计划
    [题解] LuoguP6197 [EER1]礼物
    [题解] LuoguP3980 [NOI2008]志愿者招募
  • 原文地址:https://www.cnblogs.com/habibah-chang/p/13053796.html
Copyright © 2011-2022 走看看