Minimum Threshold for Inversion Pairs Count - Problem
You are given an array of integers nums and an integer k. An inversion pair with a threshold x is defined as a pair of indices (i, j) such that:
i < jnums[i] > nums[j]- The difference between the two numbers is at most x (i.e.
nums[i] - nums[j] <= x)
Your task is to determine the minimum integer min_threshold such that there are at least k inversion pairs with threshold min_threshold. If no such integer exists, return -1.
Input & Output
Example 1 — Basic Case
$
Input:
nums = [4,3,6,2], k = 2
›
Output:
1
💡 Note:
Inversion pairs: (0,1) with diff=1, (0,3) with diff=2, (1,3) with diff=1, (2,3) with diff=4. With threshold=1, we have pairs (0,1) and (1,3), which gives us 2 pairs ≥ k=2.
Example 2 — Need Higher Threshold
$
Input:
nums = [5,4,3,2], k = 3
›
Output:
2
💡 Note:
Inversion pairs: (0,1)→1, (0,2)→2, (0,3)→3, (1,2)→1, (1,3)→2, (2,3)→1. Sorted differences: [1,1,1,2,2,3]. The 3rd smallest is 1, but we need threshold=2 to get exactly 3 pairs with diff ≤ 2.
Example 3 — No Solution
$
Input:
nums = [1,2,3], k = 1
›
Output:
-1
💡 Note:
Array is already sorted, so no inversion pairs exist. Cannot find k=1 pairs, return -1.
Constraints
- 2 ≤ nums.length ≤ 500
- 1 ≤ nums[i] ≤ 106
- 0 ≤ k ≤ n(n-1)/2
Visualization
Tap to expand
Understanding the Visualization
1
Input
Array [4,3,6,2] and k=2 (need 2+ pairs)
2
Find Pairs
Identify inversion pairs and their differences
3
Minimum Threshold
Find smallest threshold giving ≥k pairs
Key Takeaway
🎯 Key Insight: The minimum threshold is the k-th smallest difference among all inversion pairs
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code