Leetcode in Python -1052. Grumpy Bookstore Owner

Question:

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.

Solution:

Maximum number of satisfies customers = total customers - minimum unsatisfied customers
minimum unsatisfied customers = total unsatisfied customers - maximum unsatisfied customers in X time period
So the aim is to find a X time period with maximum unsatisfied customers
Here I move the X lenghth window from the left to the right of the array, each time, calculate the unsatisfied customers, and find the minimum among all the results.
To reduce complexity, use left and right to present the edge of the X length window, each time move from left to right, just add the right one and minus the (left-1) one from the result.

class Solution(object):
    def maxSatisfied(self, customers, grumpy, X):
        res = 0
        for i in range(len(customers)):
            res += customers[i]
        if len(grumpy) == X:
            return res
        diff = []
        for i in range(len(customers)):
            diff.append(customers[i] * grumpy[i])
        s =0
        for i in range(X,len(customers)):
            s += diff[i]
        temp = s
        left = 1
        right = left+X-1
        while right < len(customers):
            temp = temp + diff[left-1] - diff[right]
            if temp < s:
                s = temp
            left += 1
            right += 1
        return res - s
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值