You are tasked with analyzing inversion pairs in an array with a twist - we need to find pairs that are "close enough" in value!
Given an array of integers nums and an integer k, an inversion pair with threshold x is defined as a pair of indices (i, j) such that:
i < j(left element comes before right element)nums[i] > nums[j](left element is greater - this creates the inversion)nums[i] - nums[j] ≤ x(the difference is at most the threshold)
Your goal is to find the minimum threshold such that there are at least k inversion pairs with that threshold. If it's impossible to find k such pairs, return -1.
Example: In array [4, 1, 3, 2] with threshold 2, pairs (0,1), (0,3), (2,3) are valid inversion pairs because 4>1 (diff=3≤2 ❌), 4>2 (diff=2≤2 ✓), 3>2 (diff=1≤2 ✓).
Input & Output
Visualization
Time & Space Complexity
O(n²) to find all possible thresholds, then O(n²) for each threshold to count pairs
Store all possible threshold values (up to n² differences)
Constraints
- 2 ≤ nums.length ≤ 105
- 1 ≤ nums[i] ≤ 109
- 1 ≤ k ≤ n(n-1)/2
- All elements in nums are distinct