Beats 100%|| Simple and Easy Solution||Properly explained||T.C:O(n log n)||
Intuition\nIf the array has fewer than 5 elements (n < 5), it returns 0.\nBy sorting the array first, we can easily access the smallest and largest values.\nFor
# Intuition\nIf the array has fewer than 5 elements (n < 5), it returns 0.\nBy sorting the array first, we can easily access the smallest and largest values.\nFor arrays with 5 or more elements, the strategy to minimize the range would be to either raise the value of the smallest numbers or lower the value of the largest numbers. Since we can make at most three moves, it leaves us with a few scenarios on which numbers to change:\n1.Change the three smallest numbers..\n2.Change the two smallest numbers and the largest number.\n3.Change the smallest number and the two largest numbers.\n4.Change the three largest numbers.\n\n# Approach\nAfter sorting, the algorithm checks the length of the array.If the array has fewer than 5 elements (n < 5), it returns 0 immediately.\nIf there are 5 or more elements, the algorithm considers four possible scenarios for amending the array using at most three moves:\n1.Change the three smallest numbers (nums[n-1] - nums[3]).\n2.Change the two smallest numbers and the largest number (nums[n - 2] - nums[2]).\n3.Change the smallest number and the two largest numbers (nums[n - 3] - nums[1]).\n4.Change the three largest numbers (nums[n - 4] - nums[0]).\n\n# Complexity\n- Time complexity:\nO(nlog n).\n\n- Space complexity:\nO(1).\n\n# Code\n```\nclass Solution {\npublic:\n    int minDifference(vector<int>& nums) {\n      /*there are total four cases which can arise\n      1.Change the three smallest numbers (nums[n-1] - nums[3]). \n      2.Change the two smallest numbers and the largest number (nums[n - 2] - nums[2]).\n      3.Change the smallest number and the two largest numbers (nums[n - 3] - nums[1]).\n      4.Change the three largest numbers (nums[n - 4] - nums[0]).*/\n      int n=nums.size();\n      if(n<=4){\n        return 0;\n      }\n      int ans=INT_MAX;\n      sort(nums.begin(),nums.end());\n      for(int i=0;i<4;i++){\n        int j=3-i;\n        ans=min(ans,nums[n-1-j]-nums[i]);\n      }\n      return ans;\n    }\n};\n```
['Array', 'Math', 'Greedy', 'Brainteaser', 'Sorting', 'C++']