From cd0ad4d7d5e4a5f2c4df430994c1c47a945d61a1 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Wed, 13 Nov 2024 17:19:49 +0100 Subject: [PATCH] =?UTF-8?q?kt:=20add=20=C2=AB2563.=20Count=20the=20Number?= =?UTF-8?q?=20of=20Fair=20Pairs=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit URL: https://leetcode.com/problems/count-the-number-of-fair-pairs/ Signed-off-by: Matej Focko --- kt/count-the-number-of-fair-pairs.kt | 34 ++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 kt/count-the-number-of-fair-pairs.kt diff --git a/kt/count-the-number-of-fair-pairs.kt b/kt/count-the-number-of-fair-pairs.kt new file mode 100644 index 0000000..f4d5920 --- /dev/null +++ b/kt/count-the-number-of-fair-pairs.kt @@ -0,0 +1,34 @@ +class Solution { + private fun countFairPairsBelow( + nums: List, + 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) + ) + } +}