File tree Expand file tree Collapse file tree 2 files changed +60
-0
lines changed
leetcode/topic/sorting/1984 Expand file tree Collapse file tree 2 files changed +60
-0
lines changed Original file line number Diff line number Diff line change
1
+ // https://leetcode.com/problems/minimum-difference-between-highest-and-lowest-of-k-scores/
2
+ package main
3
+
4
+ import (
5
+ "fmt"
6
+ "math"
7
+ "sort"
8
+ )
9
+
10
+ func minimumDifference (nums []int , k int ) int {
11
+ if k == 1 {
12
+ return 0
13
+ }
14
+
15
+ sort .Ints (nums )
16
+
17
+ minDiff := math .MaxInt32
18
+
19
+ for i := 0 ; i <= len (nums )- k ; i ++ {
20
+ diff := nums [i + k - 1 ] - nums [i ]
21
+ if diff < minDiff {
22
+ minDiff = diff
23
+ }
24
+ }
25
+
26
+ return minDiff
27
+ }
28
+
29
+ func main () {
30
+ nums := []int {9 , 4 , 1 , 7 }
31
+ k := 2
32
+ result := minimumDifference (nums , k )
33
+ fmt .Println (result )
34
+ }
Original file line number Diff line number Diff line change
1
+ from typing import List
2
+
3
+ class Solution :
4
+ def minimumDifference (self , nums : List [int ], k : int ) -> int :
5
+ if k == 1 :
6
+ return 0 # If k is 1, the difference is always 0
7
+
8
+ # Sort the scores
9
+ nums .sort ()
10
+
11
+ # Initialize the minimum difference
12
+ min_diff = float ('inf' )
13
+
14
+ # Slide over the sorted array to find the minimum difference
15
+ for i in range (len (nums ) - k + 1 ):
16
+ diff = nums [i + k - 1 ] - nums [i ]
17
+ min_diff = min (min_diff , diff )
18
+
19
+ return min_diff
20
+
21
+ if __name__ == "__main__" :
22
+ solution = Solution ()
23
+ nums = [9 , 4 , 1 , 7 ]
24
+ k = 2
25
+ result = solution .minimumDifference (nums , k )
26
+ print (result )
You can’t perform that action at this time.
0 commit comments