Minimum Difference Between Largest and Smallest Value in Three Moves

medium greedy sorting array

Problem

You are given an integer array nums. In one move you may pick any element and change it to any value. After at most three moves, return the minimum possible difference between the largest and smallest value in the array.

Inputnums = [1,5,0,10,14]
Output1
Sorted: [0,1,5,10,14]. Three moves can erase any three elements; the best is to drop 5, 10, 14, leaving the gap 1 − 0 = 1.
Inputnums = [5,3,2,4]
Output0
With four or fewer elements, three moves can make every value equal, so the difference is 0.

def min_difference(nums):
    n = len(nums)
    if n <= 4:
        return 0
    nums.sort()
    best = float('inf')
    for i in range(4):
        hi = nums[n - 1 - (3 - i)]
        lo = nums[i]
        best = min(best, hi - lo)
    return best
function minDifference(nums) {
  const n = nums.length;
  if (n <= 4) return 0;
  nums.sort((a, b) => a - b);
  let best = Infinity;
  for (let i = 0; i < 4; i++) {
    const hi = nums[n - 1 - (3 - i)];
    const lo = nums[i];
    best = Math.min(best, hi - lo);
  }
  return best;
}
int minDifference(int[] nums) {
    int n = nums.length;
    if (n <= 4) return 0;
    Arrays.sort(nums);
    int best = Integer.MAX_VALUE;
    for (int i = 0; i < 4; i++) {
        int hi = nums[n - 1 - (3 - i)];
        int lo = nums[i];
        best = Math.min(best, hi - lo);
    }
    return best;
}
int minDifference(vector<int>& nums) {
    int n = nums.size();
    if (n <= 4) return 0;
    sort(nums.begin(), nums.end());
    int best = INT_MAX;
    for (int i = 0; i < 4; i++) {
        int hi = nums[n - 1 - (3 - i)];
        int lo = nums[i];
        best = min(best, hi - lo);
    }
    return best;
}
Time: O(n log n) Space: O(1)