Max Pair Sum in an Array — LeetCode 2815 Python Solution

EasyArrayHash Table
Problem
#2815
Pattern
Hash Map
Reading time
2 min

The problem

You are given an integer array nums. You have to find the maximum sum of a pair of numbers from nums such that the largest digit in both numbers is equal.

Python solution

Python
class Solution:
    def maxSum(self, nums: List[int]) -> int:
        ans = -1
        for i, x in enumerate(nums):
            for y in nums[i + 1 :]:
                v = x + y
                if ans < v and max(str(x)) == max(str(y)):
                    ans = v
        return ans

Complexity

MeasureComplexity
TimeO(n^2 \times \log M), where n is the length of the array and M is the maximum value in the array
SpaceO(n) auxiliary

Pattern: Hash Map

Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 2815. Max Pair Sum in an Array is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Hash Table.

The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2815. Max Pair Sum in an Array?
LeetCode 2815. Max Pair Sum in an Array is rated Easy on LeetCode.
What is the time complexity of LeetCode 2815. Max Pair Sum in an Array?
The Python solution on this page runs in O(n^2 \times \log M), where n is the length of the array and M is the maximum value in the array.
What is the space complexity of LeetCode 2815. Max Pair Sum in an Array?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 2815. Max Pair Sum in an Array cover?
LeetCode 2815. Max Pair Sum in an Array is tagged Array and Hash Table 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