Problem 325419 · medium · Phase 03 Linear Management & Searching

Goodwill Token

sliding window · fixed-size window · optimisation

A help desk serves visitors[i] people in minute i. The clerk is in a bad mood during minutes where moody[i] == 1, and every visitor served in a moody minute leaves unhappy; visitors in other minutes leave happy. You have one goodwill token that keeps the clerk cheerful for a block of exactly k consecutive minutes (the token's minutes count as not moody). Return the maximum number of happy visitors you can achieve by choosing when to use the token.

Examples

Input:  visitors = [1, 0, 1, 2, 1, 1, 7, 5], moody = [0, 1, 0, 1, 0, 1, 0, 1], k = 3
Output: 16
Explanation: use the token for the last 3 minutes: 1 + 1 + 1 + 1 + 7 + 5 = 16.

Input:  visitors = [1], moody = [0], k = 1
Output: 1

Constraints

  • 1 <= k <= len(visitors) == len(moody) <= 10**5
  • 0 <= visitors[i] <= 1000, moody[i] is 0 or 1
  • Target complexity: O(n) time; recomputing the total for each token position is too slow for the largest tests.

Goals

  • Separate the guaranteed part of the answer from the part a window can change
  • Maximise a fixed-size window sum over a derived array
Starting Python…