Visualize LeetCode 644 step by step. Watch binary search narrow the answer on the average, then a sliding window feasibility check verify each candidate.
About this algorithm
Find the largest average of any run of neighbouring values that is at least k long. Because the length is not fixed, a single sliding window cannot answer it directly. This page binary searches on the average itself: guess a value, ask whether any run of length k or more reaches it, and halve the range each time.
Use this when the length is "at least k" rather than "exactly k". If the length is exactly k (the easier LeetCode 643), skip all of this: the fixed sliding window page finds the best sum of k in one pass, and dividing by k gives the average. With "at least k", a longer window can beat every window of length k. For [10, 0, 10] and k = 2, both windows of length 2 average 5, but the whole array averages 6.67. The gas station page uses the same guess and check idea on a different question.
No average can be below the smallest value or above the largest, so lo = min and hi = max.
Take mid = (lo + hi) / 2 and ask: is there a run of length at least k whose average is at least mid?
Subtract mid from every value. A run averages at least mid exactly when its shifted values sum to at least 0. Keep a running prefix sum and the smallest prefix that ends at least k cells back; if the current prefix minus that minimum is 0 or more, the guess is reachable. This is one pass over the array.
If reachable, lo = mid; if not, hi = mid. Stop once hi - lo is below 0.00001.
The page loads [1, 12, -5, -6, 50, 3] with k = 4, so the search starts between -6 and 50. Guess 22: the best run, indices 1 to 4, sums to -37 after subtracting 22, so 22 is too high and hi = 22. Guess 8: the same run sums to 19, so lo = 8. Guess 15 gives -9 (hi = 15), 11.5 gives 5 (lo = 11.5), 13.25 gives -2 (hi = 13.25) and 12.375 gives 1.5 (lo = 12.375). The page draws these six and folds 17 more halvings into one step. After 23 guesses it settles on 12.75, the run 12, -5, -6, 50 at indices 1 to 4, since 51 / 4 = 12.75.
The average of a run is at least mid exactly when its sum is at least mid times its length, which is the same as the sum of (value - mid) being at least 0. Turning an average into a sum is what lets one pass with prefix sums do the check.
Time: every guess costs one O(N) pass, and halving the range from max - min down to ε takes about log2((max - min) / ε) guesses, 23 on this input. Space: the listing builds a shifted copy of the array, O(N); computing value - mid on the fly while summing brings that down to O(1).