
You are given an array 'arr' of N positive integers and an integer 'K'.
Your task is to find the minimum number of array elements you need to replace to make the sum of every contiguous subarray of length 'K' equal. You can replace an element with any integer.
The first line of input contains two space-separated integers, 'N' and 'K'.
The second line contains 'N' space-separated integers, representing the elements of the array 'arr'.
Print a single integer representing the minimum number of replacements required.
The condition that all K-length subarray sums are equal implies a periodic property. If the sum of {a_i, ..., a_{i+K-1}} must equal the sum of {a_{i+1}, ..., a_{i+K}}, it forces a_i to be equal to a_{i+K}. This means all elements at indices j, j+K, j+2K, ... must be the same for the sums to be equal with minimal changes.
5 2
3 4 3 5 6
2
To make all subarrays of length 2 have the same sum, we need `arr[i] = arr[i+2]` for all valid `i`. This creates two groups of elements that must be made equal:
Group 0 (indices 0, 2, 4): `{3, 3, 6}`. To make them equal with minimum changes, we change them to the most frequent element, which is 3. This requires 1 change (6 -> 3).
Group 1 (indices 1, 3): `{4, 5}`. To make them equal, we can change one to match the other. This requires 1 change (e.g., 5 -> 4).
Total minimum changes = 1 + 1 = 2.
5 3
1 2 3 1 2
0
The subarrays of length 3 are `{1, 2, 3}`, `{2, 3, 1}`, and `{3, 1, 2}`. All of these already have a sum of 6. No operations are needed.
Following the periodic property:
Group 0 (indices 0, 3): `{1, 1}`. Already equal. 0 changes.
Group 1 (indices 1, 4): `{2, 2}`. Already equal. 0 changes.
Group 2 (index 2): `{3}`. Already equal. 0 changes.
Total changes = 0.
The expected time complexity is O(N).
1 <= K <= N <= 10^5
1 <= arr[i] <= 10^9
Time limit: 1sec
The expected time complexity is O(N).