1509. Minimum Difference Between Largest and Smallest Value in Three Moves

You are given an integer array nums.

In one move, you can choose one element of nums and change it to any value.

Return the minimum difference between the largest and smallest value of nums after performing at most three moves.

Example 1:

Input: nums = [5,3,2,4]
Output: 0
Explanation: We can make at most 3 moves.
In the first move, change 2 to 3. nums becomes [5,3,3,4].
In the second move, change 4 to 3. nums becomes [5,3,3,3].
In the third move, change 5 to 3. nums becomes [3,3,3,3].
After performing 3 moves, the difference between the minimum and maximum is 3 - 3 = 0.

Example 2:

Input: nums = [1,5,0,10,14]
Output: 1
Explanation: We can make at most 3 moves.
In the first move, change 5 to 0. nums becomes [1,0,0,10,14].
In the second move, change 10 to 0. nums becomes [1,0,0,0,14].
In the third move, change 14 to 1. nums becomes [1,0,0,0,1].
After performing 3 moves, the difference between the minimum and maximum is 1 - 0 = 1.
It can be shown that there is no way to make the difference 0 in 3 moves.

Example 3:

Input: nums = [3,100,20]
Output: 0
Explanation: We can make at most 3 moves.
In the first move, change 100 to 7. nums becomes [3,7,20].
In the second move, change 20 to 7. nums becomes [3,7,7].
In the third move, change 3 to 7. nums becomes [7,7,7].
After performing 3 moves, the difference between the minimum and maximum is 7 - 7 = 0.

Constraints:

  • 1 <= nums.length <= 105
  • -109 <= nums[i] <= 109

Approach 01:

class Solution {
public:
    int minDifference(vector<int>& nums) {
        const int n = nums.size();
        if (n < 5) {
            return 0;
        }

        int result = INT_MAX;

        ranges::sort(nums);

        for (int i = 0; i <= 3; ++i) {
            result = min(result, nums[n - 4 + i] - nums[i]);
        }

        return result;
    }
};
class Solution:
    def minDifference(self, nums: List[int]) -> int:
        n = len(nums)
        if n < 5:
            return 0

        result = math.inf

        nums.sort()

        for i in range(4):
            result = min(result, nums[n - 4 + i] - nums[i])

        return result

Time Complexity:

  • The check if (n < 5) is done in constant time, \(O(1)\).
  • ranges::sort(nums) sorts the array nums in \(O(n \log n)\) time, where n is the size of the array.
  • The for loop for (int i = 0; i <= 3; ++i) runs a constant number of times (4 times), so it takes \(O(1)\) time.
  • Therefore, the overall time complexity is \(O(n \log n)\).

Space Complexity:

  • Sorting the array in place does not require additional space, so the space complexity for sorting is \(O(1)\) in terms of auxiliary space.
  • The additional variables take constant space, \(O(1)\).
  • Therefore, the overall space complexity is \(O(1)\).


Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top