Leetcode 1052 Grumpy Bookstore Owner. (滑动窗口)

Posted Will

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 1052 Grumpy Bookstore Owner. (滑动窗口)相关的知识,希望对你有一定的参考价值。

Leetcode 1052

问题描述

Today, the bookstore owner has a store open for customers.length minutes.  Every minute, some number of customers (customers[i]) enter the store, and all those customers leave after the end of that minute.

On some minutes, the bookstore owner is grumpy.  If the bookstore owner is grumpy on the i-th minute, grumpy[i] = 1, otherwise grumpy[i] = 0.  When the bookstore owner is grumpy, the customers of that minute are not satisfied, otherwise they are satisfied.

The bookstore owner knows a secret technique to keep themselves not grumpy for X minutes straight, but can only use it once.

Return the maximum number of customers that can be satisfied throughout the day.

例子

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.

方法

? 1. 使用滑动窗口windows记录不满意的客户数(X分钟)。当滑动窗的宽度大于X时从滑动窗的左端减去不满意的客户
? ? windows -= grumpy[i - X] * customers[i - X];
? 2. 使用satisfied记录satistified客户数量没有脾气暴躁的技术;
? 3. 在迭代结束时,satisfied+ max(winOfMakeSatisfied)是答案。

** Solution Java **
** 5ms, beats 24.57% **
** 52.9MB, beats 100.00% **
class Solution {
    public int maxSatisfied(int[] customers, int[] grumpy, int X) {
        int satisfied = 0, maxMakeSatisfied = 0, windows = 0;
        for (int i = 0; i < customers.length; ++i) {
            if (grumpy[i] == 0) 
                satisfied += customers[i];
            else
                windows += customers[i];
            if (X <= i) {
                windows -= grumpy[i - X] * customers[i - X];
            }
            maxMakeSatisfied = Math.max(maxMakeSatisfied, windows);
        }
        return satisfied + maxMakeSatisfied;
    }
}
** Solution Python3 **
** 320ms, beats 42.52% **
** 15MB, beats 100.00% **
class Solution:
    def maxSatisfied(self, customers: List[int], grumpy: List[int], X: int) -> int:
        i = win_of_make_satisfied = satisfied = max_make_satisfied = 0
        for c, g in zip(customers, grumpy):
            satisfied += (1 - g) * c
            win_of_make_satisfied += g * c
            if i >= X:
                win_of_make_satisfied -= grumpy[i - X] * customers[i - X]
            max_make_satisfied = max(win_of_make_satisfied, max_make_satisfied)  
            i += 1    
        return satisfied + max_make_satisfied

以上是关于Leetcode 1052 Grumpy Bookstore Owner. (滑动窗口)的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 1052. 爱生气的书店老板

Grumpy: Go 上运行 Python!

谷歌推出 Python 性能加速方案

224. 基本计算器│leetcode

1052:字段列表中的列“id”不明确

RT1052 BootLoader总结