Sponsored
The idea is to sort the array and find the minimal difference after removing at most three elements from either side. By sorting the array, you can easily identify the largest and smallest values that might stay in the array. After sorting, the array becomes an ordered sequence, allowing you to attempt minimizing differences by changing elements from the edges.
This approach essentially checks the possible combinations of keeping n - 3 elements and removing the smallest, or the largest, or a mix of both.
Time Complexity: O(n log n) due to sorting. Space Complexity: O(1) since the sorting is in-place.
1function minDifference(nums) {
2 if (nums.length <= 4) return 0;
3 nums.sort((a, b) =>
This JavaScript solution sorts the array using the Array.sort method with a custom comparator. The solution then calculates the possible minimum differences by analyzing four options after sorting, similar to the strategy used in other language solutions.