Problem 221129 · hard · Phase 02 Linear Data Structures

Two Lifeguard Shifts

arrays · sliding window · best-so-far

A beach counts swimmers each hour in swimmers. You may book two lifeguard shifts. Each shift covers exactly k consecutive hours, and the two shifts must not share any hour (they may touch: one can end right before the other starts). Return the largest total number of swimmers the two shifts can cover together. Counts can be negative (the sensor subtracts people who leave the water), so the best choice is not always obvious. If the day has fewer than 2 * k hours, return None.

Examples

Input:  swimmers = [1, 5, 2, 0, 0, 6, 3, 1], k = 2
Output: 16
Explanation: hours 1-2 (5 + 2) and hours 5-6 (6 + 3).

Input:  swimmers = [4, 4, 4], k = 2
Output: None

Input:  swimmers = [3, -1, 9, -8, 2], k = 1
Output: 12
Explanation: the single hours 0 and 2.

Constraints

  • 0 <= len(swimmers) <= 10**5
  • 1 <= k <= 10**5
  • -10**4 <= swimmers[i] <= 10**4
  • Target: O(n) time. Trying every pair of shifts is far too slow for the largest tests.

Goals

  • Compute every window total with a sliding sum
  • Carry the best earlier window while scanning
  • Combine two aggregates without a nested loop
Starting Python…