Make K-Subarray Sums Equal

You are given a 0-indexed integer array arr and an integer k. The array arr is circular. In other words, the first element of the array is the next element of the last element, and the last element of the array is the previous element of the first element.

You can do the following operation any number of times:

  • Pick any element from arr and increase or decrease it by 1.

Return the minimum number of operations such that the sum of each subarray of length k is equal.

A subarray is a contiguous part of the array.

Example 1
Inputarr = [1,4,1,3], k = 2
Output1
Changing the value at index 1 from 4 to 3 makes the circular length-2 subarray sums all equal to 4 using one operation.
Example 2
Inputarr = [2,5,5,7], k = 3
Output5
Changing index 0 from 2 to 5 and index 3 from 7 to 5 makes every element 5, so all circular length-3 subarray sums are 15 using five operations.

Constraints

  • 1 <= k <= arr.length <= 10^5
  • 1 <= arr[i] <= 10^9

Asked at 2 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate