#2342
Medium Algorithms Max sum of a pair with equal sum of digits
Array Hash Table Sorting Heap (Priority Queue)
66.0% acceptance
Feb 25, 2026
1405
46
You are given a 0-indexed array nums consisting of positive integers. You can choose two indices i and j, such that i != j, and the sum of digits of the number nums[i] is equal to that of nums[j].
Return the maximum value of nums[i] + nums[j] that you can obtain over all possible indices i and j that satisfy the conditions. If no such pair of indices exists, return -1.
Solution
Rust
Time O(n)
Space O(n)
use std::collections::HashMap;
impl Solution {
pub fn maximum_sum(nums: Vec<i32>) -> i32 {
let digit_sum = |mut n: i32| -> i32 {
let mut s = 0;
while n > 0 { s += n % 10; n /= 10; }
s
};
let mut best: HashMap<i32, i32> = HashMap::new();
let mut ans = -1i32;
for n in nums {
let s = digit_sum(n);
if let Some(&prev) = best.get(&s) {
ans = ans.max(prev + n);
best.insert(s, prev.max(n));
} else {
best.insert(s, n);
}
}
ans
}
}