2815. Max Pair Sum in an Array

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution {
public int maxSum(int[] nums) {
int maxSum = -1;

Map<Integer, Integer> maxDigitNumToMaxNumMap = new HashMap<>();
for (int num : nums) {
int maxDigitNum = getMaxDigitNum(num);
Integer anotherNum = maxDigitNumToMaxNumMap.get(maxDigitNum);
if (anotherNum != null) {
maxSum = Math.max(maxSum, num + anotherNum);
}
maxDigitNumToMaxNumMap.put(maxDigitNum, Math.max(num, anotherNum != null ? anotherNum : num));
}

return maxSum;
}

private int getMaxDigitNum(int num) {
int maxDigitNum = 0;
while (num != 0) {
maxDigitNum = Math.max(maxDigitNum, num % 10);
num /= 10;
}
return maxDigitNum;
}
}

References

2815. Max Pair Sum in an Array