
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Split List of Numbers to Minimize Absolute Difference of Median in Python
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
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
Advertisements