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.
Input: nums =[51,71,17,24,42]Output: 88Explanation:
Each number's largest digit in order is[5,7,7,4,4].So we have only two possible pairs,71+17=88 and 24+42=66.
For each number, group numbers by their largest digit. The answer is the maximum sum of any two numbers in the same group. We use a hash map to track the largest and second largest numbers for each digit.
classSolution {
public:int maxSum(vector<int>& nums) {
vector<int> mx(10, -1), smx(10, -1);
for (int x : nums) {
int d =0, t = x;
while (t) { d = max(d, t %10); t /=10; }
if (x > mx[d]) { smx[d] = mx[d]; mx[d] = x; }
elseif (x > smx[d]) { smx[d] = x; }
}
int ans =-1;
for (int d =0; d <10; ++d)
if (mx[d] !=-1&& smx[d] !=-1)
ans = max(ans, mx[d] + smx[d]);
return ans;
}
};
funcmaxSum(nums []int) int {
mx:= make([]int, 10)
smx:= make([]int, 10)
fori:=rangemx {
mx[i], smx[i] = -1, -1 }
for_, x:=rangenums {
d, t:=0, xfort > 0 {
ift%10 > d {
d = t%10 }
t/=10 }
ifx > mx[d] {
smx[d] = mx[d]
mx[d] = x } elseifx > smx[d] {
smx[d] = x }
}
ans:=-1ford:=0; d < 10; d++ {
ifmx[d] !=-1&&smx[d] !=-1&&mx[d]+smx[d] > ans {
ans = mx[d] +smx[d]
}
}
returnans}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
classSolution {
publicintmaxSum(int[] nums) {
int[] mx =newint[10], smx =newint[10];
Arrays.fill(mx, -1); Arrays.fill(smx, -1);
for (int x : nums) {
int d = 0, t = x;
while (t > 0) { d = Math.max(d, t % 10); t /= 10; }
if (x > mx[d]) { smx[d]= mx[d]; mx[d]= x; }
elseif (x > smx[d]) { smx[d]= x; }
}
int ans =-1;
for (int d = 0; d < 10; d++)
if (mx[d]!=-1 && smx[d]!=-1)
ans = Math.max(ans, mx[d]+ smx[d]);
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
classSolution {
funmaxSum(nums: IntArray): Int {
val mx = IntArray(10) { -1 }
val smx = IntArray(10) { -1 }
for (x in nums) {
var d = 0; var t = x
while (t > 0) { d = maxOf(d, t % 10); t /=10 }
if (x > mx[d]) { smx[d] = mx[d]; mx[d] = x }
elseif (x > smx[d]) { smx[d] = x }
}
var ans = -1for (d in0..9)
if (mx[d] != -1&& smx[d] != -1)
ans = maxOf(ans, mx[d] + smx[d])
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
classSolution:
defmaxSum(self, nums: list[int]) -> int:
mx = [-1] *10 smx = [-1] *10for x in nums:
d, t =0, x
while t:
d = max(d, t %10)
t //=10if x > mx[d]:
smx[d] = mx[d]
mx[d] = x
elif x > smx[d]:
smx[d] = x
ans =-1for d in range(10):
if mx[d] !=-1and smx[d] !=-1:
ans = max(ans, mx[d] + smx[d])
return ans