-
Notifications
You must be signed in to change notification settings - Fork 13
/
solution.java
52 lines (45 loc) · 1.46 KB
/
solution.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import java.util.Arrays;
class Solution {
public long countFairPairs(int[] nums, int lower, int upper) {
Arrays.sort(nums);
long count = 0;
int n = nums.length;
for (int i = 0; i < n - 1; i++) {
int minVal = lower - nums[i];
int maxVal = upper - nums[i];
// Find the lower bound for the range
int start = lowerBound(nums, minVal, i + 1);
// Find the upper bound for the range
int end = upperBound(nums, maxVal, i + 1);
// Add the number of valid pairs for this i
count += (end - start);
}
return count;
}
// Custom lower bound implementation
private int lowerBound(int[] nums, int target, int start) {
int low = start, high = nums.length;
while (low < high) {
int mid = low + (high - low) / 2;
if (nums[mid] < target) {
low = mid + 1;
} else {
high = mid;
}
}
return low;
}
// Custom upper bound implementation
private int upperBound(int[] nums, int target, int start) {
int low = start, high = nums.length;
while (low < high) {
int mid = low + (high - low) / 2;
if (nums[mid] <= target) {
low = mid + 1;
} else {
high = mid;
}
}
return low;
}
}