Untitled

mail@pastecode.io avatar
unknown
plain_text
2 years ago
718 B
4
Indexable
Never
public class Apple {

    public static void main(String args[]) {

        int[] A = new int[]{ 1,2,2,2,5,5, 5, 8 };
        System.out.println(minimalMoves(A));
        System.out.println(minimalMoves(new int[]{ 1, 1, 3, 4, 4, 4 }));
        System.out.println(minimalMoves(new int[]{ 1, 1, 1, 1, 3, 3, 4, 4, 4, 4, 4 }));
    }

    public static int minimalMoves(int[] A) {
        int minOps = 0;
        int j = 0;
        int frequency;
        for(int i = 0; i < A.length; i = j) {
            while (j < A.length && A[i] == A[j]) {
                j++;
            }

            frequency = j - i;
            minOps += Math.min(Math.abs(A[i] - frequency), frequency);
        }
        return minOps;
    }
}