Max Sum of a Pair With Equal Sum of Digits — LeetCode 2342 Python Solution

MediumArrayHash TableSortingHeap (Priority Queue)
Problem
#2342
Reading time
3 min

The problem

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].

Example

Input
nums = [18,43,36,13,7]
Output
54
Explanation
The pairs (i, j) that satisfy the conditions are:

Python solution

Python
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

Complexity

MeasureComplexity
TimeO(n \times \log M)
SpaceO(D) auxiliary

Pattern: Heap / Priority Queue

Keep only the best k elements, or always pull the smallest, in log time. LeetCode 2342. Max Sum of a Pair With Equal Sum of Digits is filed here because LeetCode tags it Heap (Priority Queue), which is the vocabulary this hub collects.

The heap / priority queue guide has the Python template for the pattern and the 163 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2342. Max Sum of a Pair With Equal Sum of Digits?
LeetCode 2342. Max Sum of a Pair With Equal Sum of Digits is rated Medium on LeetCode.
What is the time complexity of LeetCode 2342. Max Sum of a Pair With Equal Sum of Digits?
The Python solution on this page runs in O(n \times \log M).
What is the space complexity of LeetCode 2342. Max Sum of a Pair With Equal Sum of Digits?
The Python solution on this page uses O(D) auxiliary space.
What topics does LeetCode 2342. Max Sum of a Pair With Equal Sum of Digits cover?
LeetCode 2342. Max Sum of a Pair With Equal Sum of Digits is tagged Array, Hash Table, Sorting and Heap (Priority Queue) on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview