Problem Description
Given an array of integers, you are allowed to perform at most three moves, where in each move you can change one element to any value. The goal is to minimize the difference between the largest and smallest values in the array after performing these moves.
Key Insights
- Only three moves are allowed, so we can only adjust at most three of the extreme (smallest or largest) values.
- Sorting the array provides an ordered structure making it easier to consider which extremes to change.
- The problem reduces to picking a combination of moves (modifying some smallest and some largest numbers) such that the difference between the new extremes is minimized.
- Consider all combinations: change 0 smallest and 3 largest, 1 smallest and 2 largest, 2 smallest and 1 largest, and 3 smallest and 0 largest.
Space and Time Complexity
Time Complexity: O(n log n) due to sorting. Space Complexity: O(n) (or O(1) extra space if sorting in-place).
Solution
The solution starts by sorting the array. Once sorted, we evaluate the effect of changing different combinations of the smallest and largest elements. For each combination, if i moves are used to change the smallest values then (3 - i) moves are used to change the largest values. After these moves, the candidate difference is computed as the difference between the element at index i and the element at index n - (4 - i). The minimum of these candidate differences is the final answer.