Skip to content

Commit 2d51fad

Browse files
committed
add sol
1 parent 286c02b commit 2d51fad

File tree

2 files changed

+60
-0
lines changed

2 files changed

+60
-0
lines changed

leetcode/topic/sorting/1984/sol.go

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
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+
}

leetcode/topic/sorting/1984/sol.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
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)

0 commit comments

Comments
 (0)