码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2020-03-22 16:18:46      阅读:100      评论:0      收藏:0      [点我收藏+]

标签:customer   XSA   str   can   keep   return   NPU   max   答案   

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. (滑动窗口)

标签:customer   XSA   str   can   keep   return   NPU   max   答案   

原文地址:https://www.cnblogs.com/willwuss/p/12546080.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!