☕ Java - 8ms - Sliding Wndow - Explanation - O(NLogN)
The trick to solving this problem is realizing that we don\'t actually need to find the difference of every number within a subset of numbers of size k. Given a
The trick to solving this problem is realizing that we don\'t actually need to find the difference of every number within a subset of numbers of size k. Given a subset of size k, we only need to find the difference of the highest and lowest number.\n\nWith the above logic, it makes the most sense to start by **sorting the array.** This is because when the array is sorted, we do not have to find the largest and smallest elements in a given subarray. The largest and smallest elements will always be the last and first element in the subarray respectively.\n\nThen, we simply need to iterate over the sorted input and subtract the element at position **i (highest element in subsequence)** from the element at **position (i - k + 1)** which is the **lowest element** in the subsequence. We need to add the one because we want to include that element K positions back. As long as we continuously do this for every element in the array, we can be sure to find the minimum difference.\n\n**Runtime Complexity - O(NlogN)**\n**Memory Complexity - O(1)**\nwhere N is the size of the input array.\n```\n    public int minimumDifference(int[] nums, int k) {\n        if(k == 1) return 0;\n        \n        Arrays.sort(nums);\n        \n        int zeroIndexedK = k - 1;\n        \n        int toReturn = Integer.MAX_VALUE;\n        for(int i = zeroIndexedK; i < nums.length; i++) {\n            int highest = nums[i];\n            int lowest = nums[i - zeroIndexedK];\n            \n            int difference = highest - lowest;\n            toReturn = Math.min(toReturn, difference);\n        }\n        \n        return toReturn;\n    }\n```
['Sliding Window', 'Sorting', 'Java']