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

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
  • 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
Updated on: 2020-10-20T07:14:13+05:30

312 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements