2024.4.23力扣每日一题——爱生气的书店老板

题目来源

力扣每日一题;题序:1052

我的题解

方法一 滑动窗口

先计算不使用冷静期的总和,然后使用滑动窗口计算每个窗口内使用冷静期后能够增长的满意客户数。

时间复杂度:O( n 2 n^2 n2)
空间复杂度:O(1)

public int maxSatisfied(int[] customers, int[] grumpy, int minutes) {
    int all=0;
    int n=customers.length;
    for(int i=0;i<n;i++){
        if(grumpy[i]!=1)
            all+=customers[i];
    }
    int res=all;
    for(int i=0;i<=n-minutes;i++){
        int sub=0;
        for(int j=i;j<i+minutes;j++){
            if(grumpy[j]==1){
                sub+=customers[j];
            }
        }
        res=Math.max(res,all+sub);
    }
    return res;
}
方法二 滑动窗口+前缀和

对于滑动窗口内的计算可以使用一个前缀和数组来实现O(1)的时间复杂度。

时间复杂度:O(n)
空间复杂度:O(n)

public int maxSatisfied(int[] customers, int[] grumpy, int minutes) {
    int n = customers.length;
    int[] prefixSum = new int[n + 1];
    int all = 0;
    int res = 0;
    // 计算前缀和数组,同时更新all为所有不生气顾客的满意度总和
    for (int i = 0; i < n; i++) {
        prefixSum[i + 1] = prefixSum[i] + (grumpy[i] == 1 ? customers[i] : 0);
        all += (grumpy[i] == 0 ? customers[i] : 0);
    }
    // 使用滑动窗口找出在任何连续minutes分钟内生气顾客的满意度总和
    for (int i = 0; i + minutes <= n; i++) {
        // 计算当前窗口内生气顾客的满意度总和
        int satisfied = prefixSum[i + minutes] - prefixSum[i];
        // 更新结果res为当前窗口的总满意度和all加上当前窗口内生气顾客的满意度
        res = Math.max(res, all + satisfied);
    }
    return res;
}
方法三 滑动窗口+前缀和

官方题解的巧妙计算。

时间复杂度:O(n)
空间复杂度:O(n)

public int maxSatisfied(int[] customers, int[] grumpy, int minutes) {
   int total = 0;
   int n = customers.length;
   for (int i = 0; i < n; i++) {
       if (grumpy[i] == 0) {
           total += customers[i];
       }
   }
   int increase = 0;
   for (int i = 0; i < minutes; i++) {
       increase += customers[i] * grumpy[i];
   }
   int maxIncrease = increase;
   for (int i = minutes; i < n; i++) {
       increase = increase - customers[i - minutes] * grumpy[i - minutes] + customers[i] * grumpy[i];
       maxIncrease = Math.max(maxIncrease, increase);
   }
   return total + maxIncrease;
}

有任何问题,欢迎评论区交流,欢迎评论区提供其它解题思路(代码),也可以点个赞支持一下作者哈😄~

  • 7
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

菜菜的小彭

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值