kt: add «2342. Max Sum of a Pair With Equal Sum of Digits»

URL:	https://leetcode.com/problems/max-sum-of-a-pair-with-equal-sum-of-digits/
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2025-02-12 22:32:31 +01:00
parent fa27bdd99c
commit 3fd3eb1f4d
Signed by: mfocko
SSH key fingerprint: SHA256:icm0fIOSJUpy5+1x23sfr+hLtF9UhY8VpMC7H4WFJP8

View file

@ -0,0 +1,36 @@
class Solution {
private fun digitSum(_num: Int): Int {
var sum = 0
var num = _num
while (num > 0) {
sum += num % 10
num /= 10
}
return sum
}
fun maximumSum(nums: IntArray): Int =
mutableMapOf<Int, Int>().let { best ->
nums.withIndex().maxOf { num ->
// find the digit sum
val s = digitSum(num.value)
// construct the sum of the maximum so far and current value
val bestIndex = best.getOrDefault(s, -1)
val currentSum =
when (bestIndex) {
-1 -> -1
else -> num.value + nums[bestIndex]
}
// if found bigger value, update cached index
if (bestIndex == -1 || num.value > nums[bestIndex]) {
best[s] = num.index
}
currentSum
}
}
}