#2342

Max Sum of a Pair With Equal Sum of Digits

Medium
ArrayHash TableSortingHeap (Priority Queue)Hash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

Instead of checking all pairs, we can group numbers by their digit sums using a hash map. This allows us to efficiently find the two largest numbers for each digit sum and compute their maximum sum.

⚙️

Algorithm

4 steps
  1. 1Step 1: Create a hash map to store the largest two numbers for each digit sum.
  2. 2Step 2: Iterate through the array and calculate the digit sum for each number.
  3. 3Step 3: Update the hash map with the two largest numbers for each digit sum.
  4. 4Step 4: After processing all numbers, find the maximum sum from the values in the hash map.
solution.py22 lines
1# Full working Python code
2
3def digit_sum(n):
4    return sum(int(d) for d in str(n))
5
6def max_sum_of_pairs(nums):
7    from collections import defaultdict
8    digit_map = defaultdict(list)
9    for num in nums:
10        d_sum = digit_sum(num)
11        digit_map[d_sum].append(num)
12        if len(digit_map[d_sum]) > 2:
13            digit_map[d_sum].sort(reverse=True)
14            digit_map[d_sum] = digit_map[d_sum][:2]
15    max_sum = -1
16    for values in digit_map.values():
17        if len(values) == 2:
18            max_sum = max(max_sum, sum(values))
19    return max_sum
20
21# Example usage
22print(max_sum_of_pairs([18, 43, 36, 13, 7]))  # Output: 54

Complexity note: This complexity is due to a single pass through the array to compute digit sums and store them, leading to O(n) time. The space complexity arises from storing the numbers in the hash map.

  • 1Grouping numbers by their digit sums allows for efficient pair searching.
  • 2Using a hash map can significantly reduce the number of comparisons needed.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.