Max Sum of a Pair With Equal Sum of Digits

medium hash map digits

Problem

Given an array of positive integers nums, you may pick two different indices i and j whose numbers have the same sum of digits. Among all such pairs, return the largest possible value of nums[i] + nums[j]. If no valid pair exists, return -1.

Inputnums = [18, 43, 36, 13, 7]
Output54
18 and 36 both have digit sum 9, giving 18 + 36 = 54. 43 and 7 both have digit sum 7, giving 50. The best is 54.

def maximum_sum(nums):
    best = {}
    ans = -1
    for x in nums:
        d = sum(int(c) for c in str(x))
        if d in best:
            ans = max(ans, best[d] + x)
            best[d] = max(best[d], x)
        else:
            best[d] = x
    return ans
function maximumSum(nums) {
  const best = new Map();
  let ans = -1;
  for (const x of nums) {
    let d = 0, t = x;
    while (t > 0) { d += t % 10; t = Math.floor(t / 10); }
    if (best.has(d)) {
      ans = Math.max(ans, best.get(d) + x);
      best.set(d, Math.max(best.get(d), x));
    } else {
      best.set(d, x);
    }
  }
  return ans;
}
class Solution {
    public int maximumSum(int[] nums) {
        Map<Integer, Integer> best = new HashMap<>();
        int ans = -1;
        for (int x : nums) {
            int d = 0, t = x;
            while (t > 0) { d += t % 10; t /= 10; }
            if (best.containsKey(d)) {
                ans = Math.max(ans, best.get(d) + x);
                best.put(d, Math.max(best.get(d), x));
            } else {
                best.put(d, x);
            }
        }
        return ans;
    }
}
int maximumSum(vector<int>& nums) {
    unordered_map<int, int> best;
    int ans = -1;
    for (int x : nums) {
        int d = 0, t = x;
        while (t > 0) { d += t % 10; t /= 10; }
        if (best.count(d)) {
            ans = max(ans, best[d] + x);
            best[d] = max(best[d], x);
        } else {
            best[d] = x;
        }
    }
    return ans;
}
Time: O(n) Space: O(n)