Max Sum of a Pair With Equal Sum of Digits

Given a 0-indexed array nums of positive integers, choose two indices i != j such that the sum of digits of nums[i] equals the sum of digits of nums[j]. Return the maximum value of nums[i] + nums[j] over all such pairs, or -1 if no pair exists.

30:00

Max Sum of a Pair With Equal Sum of Digits
medium
Free written solution
Topics
Companies

Given a 0-indexed array nums of positive integers, choose two indices i != j such that the sum of digits of nums[i] equals the sum of digits of nums[j]. Return the maximum value of nums[i] + nums[j] over all such pairs, or -1 if no pair exists.

Example 1:
Input: {"nums":[18,43,36,13,7]}
Output: 54
Constraints:
  • 1≤nums.length≤1051 \leq \text{nums.length} \leq 10^5

  • 1≤nums[i]≤1091 \leq \text{nums}[i] \leq 10^9

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"nums":[18,43,36,13,7]}

Sort every number into a bucket by its digit sum. Each bucket only needs to remember its largest value, because the best partner for a newcomer is always the biggest number already in its bucket.

nums

18
43
36
13
7

digit sum

Waiting for the first number.

buckets by digit sum · champion = largest so far

no buckets yet

candidate pair

-

best answer

-1

Variables
VariableValue
answer-1
n5
DepthFunction Call
Stack empty
0/16