#C8749. Minimum Height Difference
Minimum Height Difference
Minimum Height Difference
You are given n students with their respective heights and an integer k. Your task is to select k students (not necessarily adjacent in the original order) such that the difference between the maximum and minimum heights among the selected students is minimized. In other words, if you choose a group of k students with heights \(h_1, h_2, \dots, h_k\), you need to minimize \(\max\{h_1, \dots, h_k\} - \min\{h_1, \dots, h_k\}\).
Note: To solve the problem efficiently, you may sort the list of heights and then consider every contiguous subsequence of length k.
Example:
Input: n = 7, k = 3, heights = [1, 3, 4, 9, 2, 6, 7] Output: 2</p>Explanation: After sorting the heights, we get [1, 2, 3, 4, 6, 7, 9]. The optimal group of size 3 can be [1, 2, 3] where the difference between 3 and 1 is 2.
inputFormat
The input is given from standard input (stdin) as follows:
- The first line contains two integers n and k separated by a space, where n is the number of students and k is the number of students to choose.
- The second line contains n integers separated by spaces representing the heights of the students.
Constraints:
- 1 \(\leq n \leq 10^5\)
- 1 \(\leq k \leq n\)
- Heights are positive integers.
outputFormat
The output should be printed to standard output (stdout) and consist of a single integer representing the minimum possible difference between the tallest and shortest student among any group of k students.
## sample7 3
1 3 4 9 2 6 7
2