1052. 爱生气的书店老板

from typing import List
# 这道题我是用暴力的方法来做出来的,先统计出来如果老板不能够控制住自己的脾气,应该能够使多少位顾客满意。
# 然后计算每一天应该有多少位顾客满意,写入到一个列表中去。
# 使用滑动窗口的方法,计算每一个X天老板都控制住自己的脾气,找出最大值。
class Solution:
def maxSatisfied(self, customers: List[int], grumpy: List[int], X: int) -> int:
# 求出总的天数。
length = len(customers)
# 定义一个变量,用来存放顾客最大满意的个数。
max_customer_satisfied = 0
# 如果老板不控制脾气的情况下,顾客满意的总个数。和每天顾客满意的个数。
customer_satisfied = 0
customer_satisfied_nums = [0] * length
# 分别计算这两个值。
for i in range(length):
if grumpy[i] == 0:
customer_satisfied += customers[i]
customer_satisfied_nums[i] = customers[i]
# print(customer_satisfied)
# print(customer_satisfied_nums)
# 滑动窗口,计算顾客满意最大的值。最大值的计算为:
# 滑动窗口内顾客都满意的人数 + 老板不控制脾气总顾客满意的人数 - 滑动窗口内老板不控制脾气顾客满意的人数。
for i in range(length - X + 1):
max_customer_satisfied = max(max_customer_satisfied,sum(customers[i:i + X]) + customer_satisfied - sum(customer_satisfied_nums[i:i + X]))
return max_customer_satisfied

A = Solution()
print(A.maxSatisfied(customers = [1,0,1,2,1,1,7,5], grumpy = [0,1,0,1,0,1,0,1], X = 3))
原文地址:https://www.cnblogs.com/cong12586/p/14434336.html