- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# Program to find k-sized list where difference between largest and smallest item is minimum in Python

Suppose we have a list of numbers called nums and an integer k, we have to select elements from nums to create a list of size k such that the difference between the largest integer in the list and the smallest integer is as low as possible. And we will return this difference.

So, if the input is like nums = [3, 11, 6, 2, 9], k = 3, then the output will be 4, as the best list we can make is [2, 3, 6].

To solve this, we will follow these steps −

sort the list nums

ls := a new list

for i in range 0 to size of nums - k + 1, do

insert nums[i + k - 1] - nums[i] at the end of ls

return minimum of ls

Let us see the following implementation to get better understanding −

## Example

class Solution: def solve(self, nums, k): nums.sort() ls = [] for i in range(len(nums) - k + 1): ls.append(nums[i + k - 1] - nums[i]) return min(ls) ob = Solution() nums = [3, 11, 6, 2, 9] k = 3 print(ob.solve(nums, k))

## Input

[3, 11, 6, 2, 9],3

## Output

4

- Related Questions & Answers
- Program to find minimum difference between largest and smallest value in three moves using Python
- Python program to find Largest, Smallest, Second Largest, and Second Smallest in a List?
- C++ program to find minimum possible difference of largest and smallest of crackers
- Program to find a list of numbers where each K-sized window has unique elements in Python
- C# program to find Largest, Smallest, Second Largest, Second Smallest in a List
- Program to find minimum largest sum of k sublists in C++
- Python program to find N-sized substrings with K distinct characters
- Java program to find Largest, Smallest, Second Largest, Second Smallest in an array
- Program to find length of longest sublist where difference between min and max smaller than k in Python
- Program to Find K-Largest Sum Pairs in Python
- Program to find smallest pair sum where distance is not consecutive in Python
- Find smallest and largest elements in singly linked list in C++
- C++ Program to find minimum difference between strongest and weakest
- Program to Find the longest subsequence where the absolute difference between every adjacent element is at most k in Python.
- Find minimum k records from tuple list in Python

Advertisements