Skip to content

Commit 070ca1e

Browse files
authored
Create 2563-count-the-number-of-fair-pairs.js
1 parent f2e0126 commit 070ca1e

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/**
2+
* @param {number[]} nums
3+
* @param {number} lower
4+
* @param {number} upper
5+
* @return {number}
6+
*/
7+
const countFairPairs = function(nums, lower, upper) {
8+
const n = nums.length
9+
nums.sort((a, b) => a - b)
10+
11+
let total = BigInt(n * (n - 1)) / 2n
12+
return Number(total - BigInt(large(nums, upper) + low(nums, lower)))
13+
};
14+
15+
16+
function large(arr, target) {
17+
let count = 0;
18+
for (let lo = 0, hi = arr.length - 1; lo < hi; ) {
19+
if (arr[lo] + arr[hi] > target) {
20+
count += (hi - lo);
21+
hi--;
22+
} else {
23+
lo++;
24+
}
25+
}
26+
return count;
27+
}
28+
29+
function low(arr, target) {
30+
let count = 0;
31+
for (let lo = 0, hi = arr.length - 1; lo < hi; ) {
32+
if (arr[lo] + arr[hi] < target) {
33+
count += (hi - lo);
34+
lo++;
35+
} else {
36+
hi--;
37+
}
38+
}
39+
return count;
40+
}

0 commit comments

Comments
 (0)