Max Sum of a Pair With Equal Sum of Digits — LeetCode 2342 Python Solution
- Problem
- #2342
- Pattern
- Heap / Priority Queue
- Reading time
- 3 min
- Source
- leetcode.com
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
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 ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n \times \log M) |
| Space | O(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.