You are given a 0-indexed integer array
Pick the scores of any
Return the minimum possible difference.
Output: 0
Explanation: There is one way to pick score(s) of one student:
- [90]. The difference between the highest and lowest score is 90 - 90 = 0.
The minimum possible difference is 0.
Output: 2
Explanation: There are six ways to pick score(s) of two students:
- [9,4,1,7]. The difference between the highest and lowest score is 9 - 4 = 5.
- [9,4,1,7]. The difference between the highest and lowest score is 9 - 1 = 8.
- [9,4,1,7]. The difference between the highest and lowest score is 9 - 7 = 2.
- [9,4,1,7]. The difference between the highest and lowest score is 4 - 1 = 3.
- [9,4,1,7]. The difference between the highest and lowest score is 7 - 4 = 3.
- [9,4,1,7]. The difference between the highest and lowest score is 7 - 1 = 6.
The minimum possible difference is 2.
Constraints:
1 <= k <= nums.length <= 1000 0 <= nums[i] <= 105
Contents
Solution 1 - Sort the array first, then find minimum diff window between ith index and i+kth index
In this approach, we are going to sort the input array
Implementation steps:
-
As a first step, sort the input array
nums . -
Next, create three variables
left to point to starting position of sliding window,right to point to ending position of sliding window, andmin variable to track the minimum value. We will initializeleft = 0 ,right = k-1 , because that is the starting sliding window range, and initializemin = Integer.MAX_VALUE since we are tracking minimum. -
Because the
nums array is sorted, value atleft index will have the lowest value, and the value atright index will have the highest value, take the difference between these two values and and if it is less thanmin , updatemin with new value. -
Repeat above step, until
right index reaches the end of array, and finally return themin value.
Complexity Analysis:
Time complexity: Above code runs in O(n log n) time where
Space complexity: O(1), assuming that
Above implementations source code can be found at