1052. 爱生气的书店老板(滑动窗口)

这篇博客介绍了如何运用滑动窗口优化算法来解决LeetCode上的‘爱生气的书店老板’问题。作者首先展示了原始的解决方案,然后提出了一种改进的方法,通过减少线性扫描次数提高性能。最终实现的算法能够在给定时间内计算出最大满意的客户数量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package com.heu.wsq.leetcode.slidingwindow;

/**
 * 1052. 爱生气的书店老板
 * @author wsq
 * @date 2021/2/23
 * 今天,书店老板有一家店打算试营业 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.
 *
 * 链接:https://leetcode-cn.com/problems/grumpy-bookstore-owner
 */
public class MaxSatisfied {
    /**
     * 我的笨方法,在窗口内数组求和的过程中,每次都进行了窗口的扫描,影响算法性能,
     * 这里我们可以使用滑动窗口的思想,窗口向右滑动,最左边的元素被移除,新增了最后端的元素,可以避免线性扫描求和
     * @param customers
     * @param grumpy
     * @param X
     * @return
     */
    public int myMaxSatisfied(int[] customers, int[] grumpy, int X) {
        int n = customers.length;
        int customerNum = 0;

        for(int i = 0; i < n; i++){
            if(grumpy[i] == 0){
                customerNum += customers[i];
            }
        }
        int ans = customerNum;

        for(int i = 0; i < n; i++){
            int tmp = customerNum;
            if(grumpy[i] == 1){
                // tmp += grumpy[i];
                for(int j = i; j < i + X && j < n; j++){
                    if(grumpy[j] == 1){
                        tmp += customers[j];
                    }
                }
                ans = Math.max(tmp, ans);
            }
        }
        return ans;
    }

    /**
     * 采用滑动窗口要进行性能优化,避免线性扫描求和
     * @param customers
     * @param grumpy
     * @param X
     * @return
     */
    public int maxSatisfied(int[] customers, int[] grumpy, int X) {
        int n = customers.length;
        int total = 0;
        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 += grumpy[i] * customers[i];
        }
        int maxIncrease = increase;

        for (int i = X; i < n; i++){
            increase = increase - grumpy[i - X] * customers[i - X] + grumpy[i] * customers[i];
            maxIncrease = Math.max(increase, maxIncrease);
        }
        return total + maxIncrease;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值