滑动窗口---6(稍难)
1052. 爱生气的书店老板
题目来源:1052. 爱生气的书店老板 - 力扣(LeetCode)
分析:
- 求不生气的时间最多顾客数量
- 将原始本来就不生气的时间内所有顾客累加 res
- 通过滑动grumpy来获取,在连续minutes时间内不生气导致的满意顾客增量 ans
- 最后 res += ans即时结果
答案:
class Solution:def maxSatisfied(self, customers: List[int], grumpy: List[int], minutes: int) -> int:'''customers = [1,0,1,2,1,1,7,5], grumpy = [0,1,0,1,0,1,0,1], minutes = 3遍历grumpy 滑动长度为3窗口 求生气窗口最大增值 所有不生气的时间都顾客数量 加上 最大增值 即时最后结果'''# 增值 ans = ans_tmp = 0left = 0res = 0for right,gru in enumerate(grumpy):# -----> 移入if gru == 0:res += customers[right] # 加和所有不生气的人数# 计算窗口增值if gru == 1:ans_tmp += customers[right]left = right + 1 - minutesif left < 0 :continue# 更新增值 以及对应的窗口左端点 作为该窗口标识if ans < ans_tmp:ans = max(ans,ans_tmp)# -----------> 移除if grumpy[left] == 1:tmp = customers[left]ans_tmp -= tmpres += ansreturn res
灵神:
class Solution:def maxSatisfied(self, customers: List[int], grumpy: List[int], minutes: int) -> int:s = [0, 0]max_s1 = 0for i, (c, g) in enumerate(zip(customers, grumpy)):s[g] += cif i < minutes - 1: # 窗口长度不足 minutescontinuemax_s1 = max(max_s1, s[1])if grumpy[i - minutes + 1]:s[1] -= customers[i - minutes + 1] # 窗口最左边元素离开窗口return s[0] + max_s1作者:灵茶山艾府