leetcode 2366. Minimum Replacements to Sort the Array (minimum number of replacements for array sorting)

Insert image description here

The element nums[i] in the array nums can be replaced by any two numbers a, b, provided that a+b = nums[i]. How many
replacements are needed to change the array nums into an ascending (can be equal) array.

Idea:

The sorted array is such that the left element <= the right element, with the right element as the boundary.
So the array is traversed from right to left, and the rightmost element does not need to be processed.

When splitting, it is best to divide it evenly, like 10, it is best to split it into 5 and 5, and 11 into 5 and 6. This
can ensure that when traversing to the left, the elements on the right are as large as possible to reduce splitting. frequency.
For example, [5,10,8], it is best to split 10 into 5 and 5 to get [5,5,5,8]. Then you only need to split it once.
If you split 10 into 2 and 8, you will get [5,2, 8,8], then the leftmost element 5 will be split twice.

The smallest number split (the leftmost number) is the right boundary of the next element.

If the number on the right boundary is right, then the number of splits is cnt = (nums[i] - 1) / right,
and the smallest number is nums[i] / (cnt + 1). Update right to this number.

If nums[i] itself is <=right, directly update right to nums[i] and enter the next iteration.

Pay attention to the range of values ​​and use long type for the result.

    public long minimumReplacement(int[] nums) {
    
    
       int n = nums.length;
       int right = nums[n-1];
       long res = 0;

       for(int i = n-2; i >= 0; i--) {
    
    
           if(nums[i] > right) {
    
    
               int splitCnt = (nums[i] - 1) / right;
               right = nums[i] / (splitCnt + 1);
               res += splitCnt;
           } else {
    
    
               right = nums[i];
           }
       }
       return res;
    }

Guess you like

Origin blog.csdn.net/level_code/article/details/132846794