Program to split a list of numbers such that the absolute difference of median values are smallest in Python

PythonServer Side ProgrammingProgramming

Suppose we have a list of numbers called nums, we have to divide it into two parts of same size where the absolute difference between each list's median is as small as possible and we have to find this difference. We have to keep in mind that here length of nums / 2 will be odd.

So, if the input is like [2, 10, 8, 5, 4, 7], then the output will be 2, as we can make two lists like [2,5,10] and [4,7,8], then the medians are 5 and 7, their difference is 2.

To solve this, we will follow these steps −

  • sort the list nums
  • m := quotient of size of nums/2
  • return |nums[m] - nums[m-1]|

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def solve(self, nums):
      nums.sort()
      m = len(nums)//2
      return abs(nums[m] - nums[m-1])
ob = Solution()
print(ob.solve([2, 10, 8, 5, 4, 7]))

Input

[2, 10, 8, 5, 4, 7]

Output

2
raja
Updated on 06-Oct-2020 06:29:13

Advertisements