3520. Minimum Threshold for Inversion Pairs Count π
Description
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 < j
nums[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
.
Example 1:
Input: nums = [1,2,3,4,3,2,1], k = 7
Output: 2
Explanation:
For threshold x = 2
, the pairs are:
(3, 4)
wherenums[3] == 4
andnums[4] == 3
.(2, 5)
wherenums[2] == 3
andnums[5] == 2
.(3, 5)
wherenums[3] == 4
andnums[5] == 2
.(4, 5)
wherenums[4] == 3
andnums[5] == 2
.(1, 6)
wherenums[1] == 2
andnums[6] == 1
.(2, 6)
wherenums[2] == 3
andnums[6] == 1
.(4, 6)
wherenums[4] == 3
andnums[6] == 1
.(5, 6)
wherenums[5] == 2
andnums[6] == 1
.
There are less than k
inversion pairs if we choose any integer less than 2 as threshold.
Example 2:
Input: nums = [10,9,9,9,1], k = 4
Output: 8
Explanation:
For threshold x = 8
, the pairs are:
(0, 1)
wherenums[0] == 10
andnums[1] == 9
.(0, 2)
wherenums[0] == 10
andnums[2] == 9
.(0, 3)
wherenums[0] == 10
andnums[3] == 9
.(1, 4)
wherenums[1] == 9
andnums[4] == 1
.(2, 4)
wherenums[2] == 9
andnums[4] == 1
.(3, 4)
wherenums[3] == 9
andnums[4] == 1
.
There are less than k
inversion pairs if we choose any integer less than 8 as threshold.
Constraints:
1 <= nums.length <= 104
1 <= nums[i] <= 109
1 <= k <= 109
Solutions
Solution 1
1 |
|
1 |
|
1 |
|
1 |
|