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

 Live Demo

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

Updated on: 09-Oct-2020

129 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements