## Minimum Difference Between Largest and Smallest Value in Three Moves

• Time:O(n\log n)
• Space:O(1)

## C++

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

int ans = INT_MAX;

sort(begin(nums), end(nums));

// change nums[0..i) to nums[i] and
// change nums[n - 3 + i..n) to nums[n - 4 + i]
for (int i = 0; i <= 3; ++i)
ans = min(ans, nums[n - 4 + i] - nums[i]);

return ans;
}
};
``````

## JAVA

``````class Solution {
public int minDifference(int[] nums) {
final int n = nums.length;
if (n < 5)
return 0;

int ans = Integer.MAX_VALUE;

Arrays.sort(nums);

// change nums[0..i) to nums[i] and
// change nums[n - 3 + i..n) to nums[n - 4 + i]
for (int i = 0; i <= 3; ++i)
ans = Math.min(ans, nums[n - 4 + i] - nums[i]);

return ans;
}
}
``````

## Python

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

ans = math.inf

nums.sort()

# change nums[0..i) to nums[i] and
# change nums[n - 3 + i..n) to nums[n - 4 + i]
for i in range(4):
ans = min(ans, nums[n - 4 + i] - nums[i])

return ans
``````