Simple JAVA code with detailed explanation
To minimize the diff between the max and min values, we need to alter either the values in the min range or the value in the max range. Here min range means the
To minimize the diff between the max and min values, we need to alter either the values in the min range or the value in the max range. Here min range means the minimum value and the values present close to it, and the max range means the maximum value and the values present close to it in the array. So, we just need to deal with the smallest and largest 4 values of the array. To do this, we sort our array and explore the 4 possibilities (and find the diff of the extreme values in each case):\n1. Alter the 3 values on the left and 0 values on the right.\n2. Alter the 2 values on the left and 1 value on the right.\n3. Alter the 1 value on the left and 2 values on the right.\n4. Alter the 0 values on the left and 3 values on the right.\n\nThe minimum of these 4 values is our answer. \n**Time complexity**: O(nlogn) because of sorting.\n\n```\nclass Solution {\n    public int minDifference(int[] nums) {\n        int n = nums.length;\n        if(n<5){\n            return 0;\n        }\n        Arrays.sort(nums);\n        int ans = Integer.MAX_VALUE;\n        \n        int left  = 0;\n        int right = n-4;\n        int i = 0;\n        while(i<4){\n            ans = Math.min(ans,nums[right]-nums[left]);\n            left++;\n            right++;\n            i++;\n        }\n        return ans;\n    }\n}\n
[]