Problem 360302 · hard · Phase 03 Linear Management & Searching

Best Average Over a Long Enough Stretch

binary search on the answer · prefix sums · fractions

A cyclist logs a daily score in scores (scores may be negative). The club wants to feature a contiguous stretch of at least k days whose average score is as high as possible.

Return that highest average as an exact reduced fraction [p, q]: q > 0 and gcd(|p|, q) = 1. An average of zero is [0, 1]. Only the value is returned, so ties between stretches do not matter.

Examples

Input:  scores = [1, 12, -5, -6, 50, 3], k = 4
Output: [51, 4]
Explanation: the days 12, -5, -6, 50 average 51/4 = 12.75. No stretch of 4 or more days does better.

Input:  scores = [5, 1, 5], k = 2
Output: [11, 3]
Explanation: [5, 1] and [1, 5] average 3, but all three days average 11/3 (about 3.67).

Constraints

  • 1 <= k <= len(scores) <= 10**4
  • -10**4 <= scores[i] <= 10**4
  • Checking every stretch is too slow for the largest tests.

Goals

  • Turn 'is some average at least x?' into a prefix-sum test on shifted values
  • Stop a search over real values exactly by using how close two averages can be
Starting Python…