- Choose the invariant that makes a window valid or useful.
- Advance the right boundary and add the new element.
- Move the left boundary only as needed while maintaining the invariant and updating the answer.
Code notes
- 45 lines of Java from the credited upstream file 3520.java.
- The implementation visibly relies on sequence storage.
- 3 loop blocks detected.
Complexity
Confirm that neither pointer moves backwards; if so, the scan is usually linear apart from the window’s data-structure operations.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public int minThreshold(int[] nums, int k) {3 final int mx = Arrays.stream(nums).max().getAsInt();4 int l = 0;5 int r = mx + 1;6 7 while (l < r) {8 final int m = (l + r) / 2;9 if (countInversionPairs(nums, k, m))10 r = m;11 else12 l = m + 1;13 }14 15 return l > mx ? -1 : l;16 }17 18 private boolean countInversionPairs(final int[] nums, final int k, final int threshold) {19 int inversionCount = 0;20 List<Integer> sortedNums = new ArrayList<>();21 22 for (final int num : nums) {23 final int lower = firstGreater(sortedNums, num);24 final int upper = firstGreater(sortedNums, num + threshold);25 inversionCount += upper - lower;26 sortedNums.add(lower, num);27 }28 29 return inversionCount >= k;30 }31 32 private int firstGreater(List<Integer> arr, int target) {33 int l = 0;34 int r = arr.size();35 while (l < r) {36 final int m = (l + r) / 2;37 if (arr.get(m) > target)38 r = m;39 else40 l = m + 1;41 }42 return l;43 }44}45