1 class Solution: 2 def maxSatisfied(self, customers: 'List[int]', grumpy: 'List[int]', X: int) -> int: 3 n = len(customers) 4 presum = 0 5 j = 0 6 for i in range(n): 7 if grumpy[i] == 0: 8 presum += customers[i] 9 j += 1 10 elif j < X: 11 presum += customers[i] 12 j += 1 13 14 maxsati = presum 15 for i in range(0,n-X): 16 if grumpy[i] == 1: 17 presum -= customers[i] 18 if grumpy[i+X] == 1: 19 presum += customers[i+X] 20 maxsati = max(presum,maxsati) 21 22 return maxsati
本题的思路是滑动窗口,在区间i到i+X之间,假设全部都处于平静状态,将客人的满意度都加在一起。
然后窗口向右滑动,最左侧的离开窗口,最右侧的新进入窗口,根据其原始状态,判断是进行加还是减。
具体的判断逻辑在代码的15~20行。