Computer Science, asked by lishikachaudhary9, 1 month ago

Shruti and Manas are playing with numbers. Manas gave N distinct numbers to Shruti. Shruti will insert all these N elements to a set S. Now, Manas asks Shruti to tell Kth greatest element present in the set after performing the following task: 1) Shruti has to choose all pairs of two numbers from the set and find their absolute difference an insert this difference back into the set. 2) Shruti has to perform the above operation on S until |S| no longer changes. Can you help Shruti? Input: 3 2 6 10 2 Output: 8

Answers

Answered by prabumohan9696
2

Answer:

Answer don't know

sfiydiydutd

Answered by sujan3006sl
0

Answer:

from bisect import bisect as upper_bound

def countPairs(a, n, mid):

   res = 0

   for i in range(n):

       res += upper_bound(a, a[i] + mid)

   return res

# Returns k-th absolute difference

def kthDiff(a, n, k):

   # Sort array

   a = sorted(a)

   # Minimum absolute difference

   low = a[1] - a[0]

   for i in range(1, n - 1):

       low = min(low, a[i + 1] - a[i])

   # Maximum absolute difference

   high = a[n - 1] - a[0]

   #Search for the k-th absolute difference using binary search.

   while (low < high):

       mid = (low + high) >> 1

       if (countPairs(a, n, mid) < k):

           low = mid + 1

       else:

           high = mid

   return low

k = 3

a = [1, 2, 3, 4]

n = len(a)

print(kthDiff(a, n, k))

Explanation:

Upper bound is a binary search variation that returns a reference to the first element greater than a[i] + mid from a[i] to a[n-1]. Let j be the returning pointer. After that, a[i] + mid a[j]. Subtracting (a+i+1) from this gives us the number of values with a[i] differences equal to mid. We add up all of the indices between 0 and n-1 to find the answer for the current mid.

#SPJ3

Similar questions