Skip to content
BytePatterns

Cheapest Way to Level Each Window

HardTwo Heaps & K-Way Merge#two-heaps#sliding-window#lazy-deletion~40m

Problem

You may add or subtract 1 from any value, one unit per step. For every window of k consecutive values in a list, return the fewest steps needed to make all values in that window equal. Windows are costed independently, and the list itself never changes. There are up to 100,000 values and k can be as large as the list.

Examples

Input:  nums = [1, 3, 2, 8, 5, 5], k = 3
Output: [2, 6, 6, 3]
Why:    [3, 2, 8] is levelled to its median 3 for 1 + 0 + 5 = 6 steps
Input:  nums = [4, 4, 4, 1], k = 2
Output: [0, 0, 3]
Why:    the last window [4, 1] costs 3 whichever value both end up at between 1 and 4
Input:  nums = [7, 2, 9], k = 1
Output: [0, 0, 0]
Why:    edge case, a single value is already level

Hints

0 / 3

Stuck on the idea rather than the code? Sliding Window Median covers it.