Show problems as
Classic problem #2342MediumArrayHash TableSortingHeap (Priority Queue)

Max Sum of a Pair With Equal Sum of Digits

Real-world version: The Heaviest Pair With Matching Digit Totals
Tracked in this browser only
Read Max Sum of a Pair With Equal Sum of Digits on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

A list of positive whole numbers reads values. The digit total of a number is what its decimal digits add up to.

Return the largest amount any two values at different positions add up to, given that their digit totals match, or -1 when no two positions have matching digit totals.

Examples

Example 1

Input
values = [51, 71, 17, 42]
Output
93

The digit totals are six, eight, eight and six. The pair on six adds to ninety-three and the pair on eight to eighty-eight, so ninety-three wins.

Example 2

Input
values = [1, 2, 3]
Output
-1

The three digit totals are all different, so no pair qualifies.

Example 3

Input
values = [9, 90, 900]
Output
990

All three values have a digit total of nine, so the two largest pair up.

Constraints

  • 1 <= values.length <= 10^5
  • 1 <= values[i] <= 10^9

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def maximum_sum(values: list[int]) -> int:
Java
public int maximumSum(int[] values)