Simple and Beginner-Friendly Solution w/ Sorting and Greedy Method 😊😊
Intuition\nThe problem asks us to find the minimum difference between three numbers from a given list. The key is to realize that we can achieve the smallest di
# Intuition\nThe problem asks us to find the minimum difference between three numbers from a given list. The key is to realize that we can achieve the smallest difference by focusing on the extremes of the sorted list. If we pick three numbers from the extremes (smallest and largest), we are likely to find the smallest difference.\n\n# Approach\n1. Sort the input list: This will allow us to easily access the smallest and largest numbers.\n2. Iterate through possible combinations: We need to consider all possible combinations of three numbers that can be selected from the sorted list.\n3. Calculate the difference: For each combination, calculate the difference.\n4. Update the minimum difference: Keep track of the minimum difference found so far and update it if a smaller difference is encountered.\n5. Return the minimum difference: After iterating through all possible combinations, return the minimum difference.\n\n# Complexity\n- Time complexity: O(n log n)\n\n- Space complexity: O(1)\n\n# Code\n```\n/**\n * @param {number[]} nums\n * @return {number}\n */\nvar minDifference = function (nums) {\n  if (nums.length <= 3) {\n    return 0;\n  }\n\n  let min = Infinity;\n  nums = nums.sort((a, b) => a - b);\n\n  let left = 0;\n  let right = nums.length - 1;\n\n  // left left left\n  min = Math.min(min, Math.abs(nums[left + 3] - nums[right]));\n\n  // left left right\n  min = Math.min(min, Math.abs(nums[left + 2] - nums[right - 1]));\n\n  // left right right\n  min = Math.min(min, Math.abs(nums[left + 1] - nums[right - 2]));\n\n  // right right right\n  min = Math.min(min, Math.abs(nums[left] - nums[right - 3]));\n\n  return min;\n};\n```
['Array', 'Greedy', 'Sorting', 'JavaScript']