[leetcode] 1052. Grumpy Bookstore Owner

Description

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.

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. 1 <= X <= customers.length == grumpy.length <= 20000.
  2. 0 <= customers[i] <= 1000.
  3. 0 <= grumpy[i] <= 1.

分析

题目的意思是:给你一个数组,把其中grumpy为0的位置加起来,然后给了你一个X,你可以把X范围内的数也加起来,求总的最大值。我第一次看题目没看懂,后面发现懂了,好像X就是一个窗口,除了为0的位置的数,还有滑动窗口里面的数也要加起来。我顿时看见这个慌了神,看了别人的参考代码才发现需要用一个滑动窗口找到X覆盖范围的最大值,然后重新加上grumpy位置为0的数就行了。

代码

class Solution:
    def maxSatisfied(self, customers: List[int], grumpy: List[int], X: int) -> int:
        i=0
        max_save=0
        cur=0
        n=len(customers)
        for j in range(n):
            if(j-i+1>X):
                if(grumpy[i]):
                    cur-=customers[i]
                i+=1
            if(grumpy[j]):
                cur+=customers[j]
                max_save=max(max_save,cur)
                
        s=sum(customers[i] for i in range(n) if(grumpy[i]==0))
        return s+max_save
        

参考文献

[LeetCode] Python 3 Sliding window

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

农民小飞侠

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

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

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

打赏作者

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

抵扣说明:

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

余额充值