Program to count maximum number of distinct pairs whose differences are larger than target in Python

PythonServer Side ProgrammingProgramming

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
  • return ans

Let us see the following implementation to get better understanding −

Example

 Live Demo

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
raja
Published on 20-Oct-2020 10:43:32
Advertisements