kt: add «2563. Count the Number of Fair Pairs»
URL: https://leetcode.com/problems/count-the-number-of-fair-pairs/ Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
b0a4c140be
commit
cd0ad4d7d5
1 changed files with 34 additions and 0 deletions
34
kt/count-the-number-of-fair-pairs.kt
Normal file
34
kt/count-the-number-of-fair-pairs.kt
Normal file
|
@ -0,0 +1,34 @@
|
||||||
|
class Solution {
|
||||||
|
private fun countFairPairsBelow(
|
||||||
|
nums: List<Int>,
|
||||||
|
upper: Int,
|
||||||
|
): Long {
|
||||||
|
var pairs = 0L
|
||||||
|
|
||||||
|
var (left, right) = 0 to nums.size - 1
|
||||||
|
while (left < right) {
|
||||||
|
val sum = nums[left] + nums[right]
|
||||||
|
|
||||||
|
if (sum < upper) {
|
||||||
|
pairs += right - left
|
||||||
|
left += 1
|
||||||
|
} else {
|
||||||
|
right -= 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return pairs
|
||||||
|
}
|
||||||
|
|
||||||
|
fun countFairPairs(
|
||||||
|
nums: IntArray,
|
||||||
|
lower: Int,
|
||||||
|
upper: Int,
|
||||||
|
): Long {
|
||||||
|
val sortedNums = nums.sorted()
|
||||||
|
return (
|
||||||
|
countFairPairsBelow(sortedNums, upper + 1) -
|
||||||
|
countFairPairsBelow(sortedNums, lower)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in a new issue