Back to questions
Given an integer array , the difference between the largest and smallest values is called amplitude. If you can change up to three elements of the array to any value, return the minimum possible amplitude.
Input: arr = [4, -8, -1, 3, 7, 10, 5]
Output: 4
Explanation: By changing -8 and -1 to 3, and 10 to 7, the array can be transformed into [4, 3, 3, 3, 7, 7, 5]. The new maximum value is 7 and the new minimum value is 3, resulting in an amplitude of 7 - 3 = 4.
Input: arr = [3, 5, 10, 0]
Output: 0
Explanation: We can change 3, 5, and 10 to 0, resulting in the array [0, 0, 0, 0]. Since all values are the same, the maximum and minimum values are both 0, leading to an amplitude of 0 - 0 = 0.
To minimize the amplitude of the array, we need to focus on reducing the gap between the largest and smallest values. Since we can change up to three numbers to any value, we should aim to make extreme values (either the largest or smallest) closer together.
Here's the idea:
For instance, let’s consider an example:
Given an array:
Suppose we make these changes:
With these changes, our new amplitude is .
But, we still have the option to change one more element! By changing either the next smallest or next largest value, we might make the amplitude even smaller. It’s important to explore different options, since sometimes changing the three largest or three smallest values (or a combination) gives the smallest possible amplitude.
To simplify this process, we can sort the array. Sorting allows us to efficiently find the next largest or smallest values after each potential change.
With a sorted array, we can try four main cases:
After trying all four combinations, we take the smallest difference among them.
If the array has fewer than 5 elements, we can return immediately since we can change all elements to be the same.
Here is the code: