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:
parent
fa27bdd99c
commit
3fd3eb1f4d
1 changed files with 36 additions and 0 deletions
36
kt/max-sum-of-a-pair-with-equal-sum-of-digits.kt
Normal file
36
kt/max-sum-of-a-pair-with-equal-sum-of-digits.kt
Normal 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
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue