
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
Count Maximum Number of Distinct Pairs in Python
Suppose we have a list of numbers called nums and another value target. We have to find the maximum number of pairs where for each pair i < j, i and j are not in any other pair, and |nums[i] - nums[j]| >= target.
So, if the input is like nums = [2, 4, 6, 10, 11], target = 5, then the output will be 2, as we can get pairs: (2, 6), (5, 10)
To solve this, we will follow these steps −
- N := size of A
- sort the list A
- ans := 0
- j := N / 2
- for i in range 0 to N / 2, do
- while j < N and A[j] - A[i] < target, do
- j := j + 1
- if j < N, then
- ans := ans + 1
- j := j + 1
- while j < N and A[j] - A[i] < target, do
- return ans
Let us see the following implementation to get better understanding −
Example
class Solution: def solve(self, A, target): N = len(A) A.sort() ans = 0 j = N >> 1 for i in range(N >> 1): while j < N and A[j] - A[i] < target: j += 1 if j < N: ans += 1 j += 1 return ans ob = Solution() nums = [2, 4, 6, 10, 11] target = 5 print(ob.solve(nums, target))
Input
[2, 4, 6, 10, 11], 5
Output
2
Advertisements