imashutosh51

Count Pairs Whose Sum is Less than Target

Aug 10th, 2022 (edited)
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.42 KB | None | 0 0
  1. //first approach is brute force
  2. class Solution:
  3.     def countPairs(self, nums: List[int], target: int) -> int:
  4.         arr=sorted(nums)
  5.         i,j=0,len(arr)-1
  6.         ans=0
  7.         while i<=j:
  8.             if arr[i]+arr[j]>=target:
  9.                 j-=1
  10.             elif arr[i]+arr[j]<target: #arr[i] can form valid pairs with every element from i+1 to j
  11.                 ans+= (j-i)
  12.                 i+=1
  13.         return ans
Advertisement
Add Comment
Please, Sign In to add comment