#K60257. Minimum Difference in a Subarray
Minimum Difference in a Subarray
Minimum Difference in a Subarray
Given an array of N integers and an integer K, your task is to compute the minimum possible difference between the maximum and minimum values among any selection of K numbers chosen from the array after sorting. In other words, after sorting the array, you need to find a window of K consecutive elements such that the difference (\text{diff} = a_{i+K-1} - a_i) is minimized.
The problem can be mathematically formulated as follows: Given a sorted array (a_1 \le a_2 \le \cdots \le a_N), find (\min_{1 \le i \le N-K+1} (a_{i+K-1} - a_i)).
inputFormat
The first line contains two integers N and K, where N is the number of elements in the array and K is the subarray (window) size. The second line contains N space-separated integers representing the elements of the array.
outputFormat
Output a single integer which is the minimum difference between the maximum and minimum values in any subarray (window) of length K after sorting the array.## sample
7 3
10 1 5 9 3 8 12
2