0-indexed 정수 배열 num이 주어집니다. 여기서 nums[i]는 ith 학생의 점수를 나타냅니다. 또한 정수 k가 주어집니다.
배열에서 k 학생의 점수를 선택하여 k점 중 가장 높은 점수와 가장 낮은 점수의 차이를 최소화합니다.
가능한 최소 차액을 반환합니다.
https://leetcode.com/problems/minimum-difference-between-highest-and-lowest-of-k-scores/
You are given a 0-indexed integer array nums, where nums[i] represents the score of the ith student. You are also given an integer k.
Pick the scores of any k students from the array so that the difference between the highest and the lowest of the k scores is minimized.
Return the minimum possible difference.
Example 1:
Input: nums = [90], k = 1
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.
Example 2:
Input: nums = [9,4,1,7], k = 2
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.
자바입니다.
class Solution {
public int minimumDifference(int[] nums, int k) {
if(nums.length==1) return 0;
Arrays.sort(nums);
int min=100000;
for(int i=nums.length-1;i>=0;i--){
if(i-k+1>-1&&nums[i]-nums[i-k+1]<min) min=nums[i]-nums[i-k+1];
}
return min;
}
}