#2815
Easy Algorithms Max pair sum in an array
Array Hash Table
60.4% acceptance
Feb 25, 2026
436
137
You are given an integer array nums. You have to find the maximum sum of a pair of numbers from nums such that the largest digit in both numbers is equal.
For example, 2373 is made up of three distinct digits: 2, 3, and 7, where 7 is the largest among them.
Return the maximum sum or -1 if no such pair exists.
Solution
Rust
Time O(n)
Space O(1)
impl Solution {
pub fn max_sum(nums: Vec<i32>) -> i32 {
let max_digit = |mut n: i32| -> i32 { let mut mx = 0; while n > 0 { mx = mx.max(n % 10); n /= 10; } mx };
let mut groups = [0i32; 10];
let mut ans = -1i32;
for &n in &nums {
let key = max_digit(n) as usize;
if groups[key] > 0 { ans = ans.max(groups[key] + n); }
if n > groups[key] { groups[key] = n; }
}
ans
}
}