- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Advertisements