当前位置:网站首页>Leetcode minimum difference in student scores

Leetcode minimum difference in student scores

2022-07-07 05:00:00 kt1776133839

Title Description :

To give you one Subscript from 0 Start Array of integers for nums , among nums[i] It means the first one i A student's grade . I'll give you another integer k .

Select any... From the array k A student's grade , Make this k Between scores The highest and Lowest score Of Difference value achieve To minimize the .

Return possible Minimum difference .

Examples :

Example 1:

Input :nums = [90], k = 1
Output :0
explain : elect 1 A student's grade , have only 1 Methods :
- [90] The difference between the highest score and the lowest score is 90 - 90 = 0
The smallest possible difference is 0

Example 2:

Input :nums = [9,4,1,7], k = 2
Output :2
explain : elect 2 A student's grade , Yes 6 Methods :
- [9,4,1,7] The difference between the highest score and the lowest score is 9 - 4 = 5
- [9,4,1,7] The difference between the highest score and the lowest score is 9 - 1 = 8
- [9,4,1,7] The difference between the highest score and the lowest score is 9 - 7 = 2
- [9,4,1,7] The difference between the highest score and the lowest score is 4 - 1 = 3
- [9,4,1,7] The difference between the highest score and the lowest score is 7 - 4 = 3
- [9,4,1,7] The difference between the highest score and the lowest score is 7 - 1 = 6
The smallest possible difference is 2

Tips :

  • 1 <= k <= nums.length <= 1000
  • 0 <= nums[i] <= 105

Java Program :

class Solution {
    public int minimumDifference(int[] nums, int k) {
        Arrays.sort(nums);
        int ans=nums[k-1]-nums[0];
        for(int i=1;i<=nums.length-k;i++){ans=Math.min(ans,nums[i+k-1]-nums[i]);}
        return ans;
    }
}

原网站

版权声明
本文为[kt1776133839]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202130740485346.html