Make K-Subarray Sums Equal - Problem
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
arrand 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.
Input & Output
Example 1 — Basic Circular Array
$
Input:
arr = [2,5,3,9,5,3], k = 3
›
Output:
5
💡 Note:
Need to make all 3-subarrays equal: [2,5,3], [5,3,9], [3,9,5], [9,5,3], [5,3,2], [3,2,5]. Optimal solution groups elements by GCD pattern and uses medians.
Example 2 — Small Array
$
Input:
arr = [1,4,1,3], k = 2
›
Output:
1
💡 Note:
4-subarrays of length 2: [1,4], [4,1], [1,3], [3,1]. Elements at even positions (1,1) and odd positions (4,3) form groups. Operations: |1-1| + |4-3.5| + |1-1| + |3-3.5| = 1
Example 3 — No Operations Needed
$
Input:
arr = [2,2,2,2], k = 2
›
Output:
0
💡 Note:
All elements are already equal, so all k-subarrays have equal sums. No operations needed.
Constraints
- 1 ≤ arr.length ≤ 105
- 1 ≤ arr[i] ≤ 109
- 1 ≤ k ≤ arr.length
Visualization
Tap to expand
Understanding the Visualization
1
Input
Circular array [2,5,3,9,5,3] with k=3 subarrays
2
Process
Group elements by GCD pattern and find optimal values
3
Output
Minimum 5 operations to equalize all k-subarray sums
Key Takeaway
🎯 Key Insight: Elements at positions with same remainder mod gcd(n,k) must be equal
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code