Skip to main content
Back to problems
Leetcode
Medium
Arrays
Hash Maps
Math
Max Sum Of A Pair With Equal Sum Of Digits

Find the maximum possible sum of two distinct numbers whose digit sums are equal.

Acceptance 0%
Problem Statement

Problem

You are given an array of integers. Your task is to choose two different elements such that the sum of their decimal digits is the same for both numbers.

Among all valid pairs, return the largest possible value of a + b. If no such pair exists, return -1.

A pair is considered distinct if it uses two different array positions.

Notes

  • The digit sum of a non-negative integer is the sum of all digits in its base-10 representation.
  • If multiple pairs have the same digit-sum condition, only the pair with the maximum total matters.

Input Format

  • An integer array nums
  • Each element is treated as a base-10 integer when computing digit sum

Output Format

  • Return a single integer: the maximum sum of a valid pair, or -1 if no valid pair exists

Constraints

  • Use two distinct elements from the array
  • A valid pair must have equal digit sums
  • If no valid pair exists, return -1
Examples
Sample cases returned by the problem API.

Example 1

Input

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

Output

54

Explanation

Digit sums are: 18→9, 43→7, 36→9, 13→4, 7→7. The valid pairs are (18,36) with sum 54 and (43,7) with sum 50. The maximum is 54.

Example 2

Input

nums = [10, 12, 19, 14]

Output

-1

Explanation

Digit sums are 1, 3, 10, and 5. No two numbers share the same digit sum.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.