Max Sum of a Pair With Equal Sum of Digits Problem
Description
LeetCode Problem 2342.
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. If no such pair of indices exists, return -1.
Example 1:
Input: nums = [18,43,36,13,7]
Output: 54
Explanation: The pairs (i, j) that satisfy the conditions are:
- (0, 2), both numbers have a sum of digits equal to 9, and their sum is 18 + 36 = 54.
- (1, 4), both numbers have a sum of digits equal to 7, and their sum is 43 + 7 = 50.
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:
1 <= nums.length <= 10^51 <= nums[i] <= 10^9
Solution
Approach: Hash Table by Digit Sum
Group the numbers by their digit sum, and for each digit sum remember only the largest number seen so far. Go through nums: for each v with digit sum x, if x already has a stored number, stored + v is a candidate answer; then update the stored maximum with v. The answer starts at -1 and is the largest candidate.
Since v <= 10^9, a digit sum is at most 81, so an array of size 100 can replace the hash table.
Complexity: Time O(n log M) for the digit sums, space O(D), where M <= 10^9 is the largest value and D <= 81 the largest digit sum.
from collections import defaultdict
class Solution:
def maximumSum(self, nums: List[int]) -> int:
d = defaultdict(int)
ans = -1
for v in nums:
x, y = 0, v
while y:
x += y % 10
y //= 10
if x in d:
ans = max(ans, d[x] + v)
d[x] = max(d[x], v)
return ans