https://www.geeksforgeeks.org/minimum-number-of-moves-to-make-all-elements-equal/
Given an array containing N elements and an integer K. It is allowed to perform the following operation any number of times on the given array:
- Insert the K-th element at the end of the array and delete the first element of the array.
The task is to find the minimum number of moves needed to make all elements of the array equal. Print -1 if it is not possible.
Examples:
Input : arr[] = {1, 2, 3, 4}, K = 4 Output : 3 Step 1: 2 3 4 4 Step 2: 3 4 4 4 Step 3: 4 4 4 4 Input : arr[] = {2, 1}, K = 1 Output : -1 The array will keep alternating between 1, 2 and 2, 1 regardless of how many moves you apply.
Let’s look at the operations with respect to the original array, first we copy a[k] to the end, then a[k+1] and so on. To make sure that we only copy equal elements, all elements in the range K to N should be equal.
So, to find the minimum number of moves, we need to remove all elements in range 1 to K that are not equal to a[k]. Hence, we need to keep applying operations until we reach the rightmost term in range 1 to K that is not equal to a[k].