LeetCode-in-Java

2342. Max Sum of a Pair With Equal Sum of Digits

Medium

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.

Example 1:

Input: nums = [18,43,36,13,7]

Output: 54

Explanation: The pairs (i, j) that satisfy the conditions are:

So the maximum sum that we can obtain is 54.

Example 2:

Input: nums = [10,12,19,14]

Output: -1

Explanation: There are no two numbers that satisfy the conditions, so we return -1.

Constraints:

Solution

import java.util.HashMap;
import java.util.Map;

public class Solution {
    public int maximumSum(int[] nums) {
        Map<Integer, Integer> map = new HashMap<>();
        int res = -1;
        for (int num : nums) {
            int s = 0;
            for (char digit : String.valueOf(num).toCharArray()) {
                s += Integer.valueOf(digit - '0');
            }
            if (!map.containsKey(s)) {
                map.put(s, num);
            } else {
                res = Math.max(res, map.get(s) + num);
                map.put(s, Math.max(map.get(s), num));
            }
        }
        return res;
    }
}