SlidingWindow - 1984. Minimum Difference Between Highest and Lowest of K Scores

SlidingWindow - 1984. Minimum Difference Between Highest and Lowest of K Scores

https://leetcode.com/problems/minimum-difference-between-highest-and-lowest-of-k-scores/description/

We can start first by removing the special cases when k=1 or when the length of the nums is less than the given k

Then for avoiding a lot of not needed calculations we can sort the array

Without sorting

[9,4,1,7]
9,4
9,1
9,7
4,1
4,7
1,7        

With Sorting

[1,4,7,9]
1,4
4,7
7,9        

The last step is to apply the sliding window with the given k as the length of the window and determine the minimum difference.

class Solution {
    public int minimumDifference(int[] nums, int k) {
        if(k == 1 || nums.length < k)
            return 0;

        Arrays.sort(nums);
        int min = nums[k-1] - nums[0];

        for(int i=1; i<=nums.length-k; i++){
            int diff = nums[i+k-1] - nums[i];
            if(diff < min)
                min = diff;
        }

        return min;
    }
}        


#sliding_window

要查看或添加评论,请登录

Hossam El Deen Abdallah的更多文章

社区洞察

其他会员也浏览了