- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions

# Program to count maximum number of distinct pairs whose differences are larger than target 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

- Related Articles
- Program to count number of fraction pairs whose sum is 1 in python
- Count number of distinct pairs whose sum exists in the given array in C++
- Program to find lowest sum of pairs greater than given target in Python
- Program to find number of distinct quadruple that forms target sum in python
- Program to count number of distinct substrings in s in Python
- Program to find number of sublists whose sum is given target in python
- Program to check number of triplets from an array whose sum is less than target or not Python
- Program to count number of permutations where sum of adjacent pairs are perfect square in Python
- Program to count minimum number of operations to flip columns to make target in Python
- Program to find maximum number of K-sized groups with distinct type items are possible in Python
- Program to find minimum number of subsequence whose concatenation is same as target in python
- Program to count number of paths whose sum is k in python
- Program to count number of distinct characters of every substring of a string in Python
- Program to find number of pairs between x, whose multiplication is x and they are coprime in Python
- Python program to count distinct words and count frequency of them

Advertisements