Problem statement

https://binarysearch.com/problems/Largest-and-Smallest-Difference/

Solution

Sort our numbers and then use sliding window of length k.

Complexity

It is O(n log n) for time and O(n) for space.

Code

class Solution:
    def solve(self, nums, k):
        nums = sorted(nums)
        n = len(nums)
        ans = float("inf")
        for i in range(n - k + 1):
            ans = min(ans, nums[i+k-1] - nums[i])

        return ans