Ctrl K

Equal Window Sums on a Ring

Medium
The numbers of ring stand in a circle: the first element follows the last one. A *window* is width consecutive elements going around the circle from any starting position, so there are as many windows as elements. In one step you may raise or lower any element by 1. What is the smallest number of steps after which every window has the same sum?
Example 1
ring=[3, 7, 3, 5], width=2 → 2

The circular windows of length 2 are 3+7, 7+3, 3+5, 5+3. For all sums to match, every other element must be equal, so 7 and 5 must meet: that costs 2 steps (for example 7 → 5).

Example 2
ring=[4, 1, 6, 2, 8, 3], width=4 → 6

With n = 6 and windows of 4, elements at indices of the same parity must end up equal: [4, 6, 8] and [1, 2, 3]. Pulling them to the medians 6 and 2 costs 2 + 2 + 1 + 1 = 6.

Example 3
ring=[9, 2, 5], width=3 → 0

A window of 3 on a ring of three numbers always covers everything, so every sum is already the same.

Constraints
  • 1 ≤ width ≤ len(ring) ≤ 10⁵
  • 1 ≤ ring[i] ≤ 10⁹
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsUp or Down for Every Post MediumRound Prices to a Total MediumThe Middle Bag MediumPrices That Fade With Each Sale MediumSame Prizes, Different Tastes Medium
loading Python…
Input
ring=[3, 7, 3, 5], width=2
Expected
2

Run checks the first 3 tests in your browser. Submit checks all 103 tests on the server, hidden ones included.