2342.js
/** ------------------------------------------------------------------------------
*
* 2342. Max Sum of a Pair With Equal Sum of Digits
* Topics: Hash Map
* https://leetcode.com/problems/max-sum-of-a-pair-with-equal-sum-of-digits/?envType=daily-question&envId=2025-02-12
*
------------------------------------------------------------------------------ */
/**
* @param {number[]} nums
* @return {number}
*/
var maximumSum = function (nums) {
const map = new Map()
let max = -1
const getSum = (num) => {
return num
.toString()
.split("")
.reduce((acc, cur) => acc + Number(cur), 0)
}
/**
* getSum 함수의 시간복잡도를 약간 더 개선한다면
*/
// function getSum(num) {
// let sum = 0;
// while (num > 0) {
// sum += num % 10;
// num = Math.floor(num / 10);
// }
// return sum;
// }
for (let num of nums) {
let sum = getSum(num)
if (map.has(sum)) {
max = Math.max(max, num + map.get(sum))
map.set(sum, Math.max(map.get(sum), num))
} else {
map.set(sum, num)
}
}
return max
}
console.log(maximumSum([18, 43, 36, 13, 7]))