- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies

- 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 Articles
- 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?
- Program to find a list of numbers where each K-sized window has unique elements in Python
- C++ program to find minimum possible difference of largest and smallest of crackers
- 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
- 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
- Java program to find Largest, Smallest, Second Largest, Second Smallest in an array
- 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
- Program to find smallest value of K for K-Similar Strings in Python
- Python Program To Find the Smallest and Largest Elements in the Binary Search Tree
- Program to find smallest pair sum where distance is not consecutive in Python

Advertisements