Problem statement

https://binarysearch.com/problems/Angry-Owner/

Solution

Equal to Leetcode 1052. Grumpy Bookstore Owner.

Complexity

It is O(n) for time and space.

Code

class Solution:
    def solve(self, arr, G, M):
        ans = sum(x*y for x, y in zip(arr, G))
        cost = [x*(1-y) for x, y in zip(arr, G)]
        acc = [0] + list(accumulate(cost))
        gain = max(acc[i] - acc[i - M] for i in range(M, len(acc)))
        return ans + gain