LeetCode/kt/max-sum-of-a-pair-with-equal-sum-of-digits.kt

36 lines
999 B
Kotlin

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
}
}
}