Small application of greedy algorithm

After reading the question, I thought about how to find the minimum number of operations for each change. The array is unordered at the beginning, so there is no way to clearly understand the number of operations, so first sort the array, after sorting , Verify if each number is greater than the previous one, it will satisfy the smallest operand, the proof is as follows:
Assuming that the A array is ordered, then the previous number must be smaller than the following number, if a certain number wants to become The number different from the one before him must be added all the time. At this time, considering that the latter number can become the number that you want to become faster, but the number we skipped must become a larger number. So the above result is true: the
code is as follows

    public int minIncrementForUnique(int[] A) {
        Arrays.sort(A);
        int res=0;
        for(int i=1;i<A.length;i++){
            if(A[i]>A[i-1]) continue;
            res=res+A[i-1]+1-A[i];
            A[i]=A[i-1]+1;
        }
        return res;
    }

 

Published 17 original articles · praised 0 · visits 153

Guess you like

Origin blog.csdn.net/qq_33286699/article/details/105030989