2815. Max Pair Sum in an Array
Problem Description
You are given an integer array nums
. Your task is to find the maximum sum of a pair of numbers from this array, with a special condition: both numbers in the pair must have the same largest digit.
To understand what "largest digit" means, consider the number 2373. This number contains the digits 2, 3, 7, and 3. Among these digits, 7 is the largest.
Here's what you need to do:
- Find all possible pairs of numbers from the array
- For each pair, check if both numbers have the same largest digit
- If they do, calculate their sum
- Return the maximum sum among all valid pairs
If no pair exists where both numbers have the same largest digit, return -1.
For example:
- If
nums = [51, 71, 17, 42]
- 51 has largest digit 5
- 71 has largest digit 7
- 17 has largest digit 7
- 42 has largest digit 4
- The pairs (71, 17) both have largest digit 7, so their sum 71 + 17 = 88 would be a valid candidate
- Since this is the only valid pair, the answer would be 88
Intuition
When we need to find the maximum sum of a pair with a specific constraint, the most straightforward approach is to check all possible pairs. Since we're looking for a maximum value and have a filtering condition (same largest digit), a brute force approach makes sense here.
The key insight is that we need to:
- Compare every possible pair of numbers in the array
- For each pair, determine if they meet our condition (same largest digit)
- Keep track of the maximum sum we've seen so far
To find the largest digit in a number, we can convert the number to a string and use the max()
function on the string representation. For example, max(str(2373))
would give us '7'
, which is exactly what we need.
The nested loop structure naturally emerges from the need to examine all pairs. For each number at position i
, we check it against all numbers that come after it (positions i+1
to the end). This ensures we don't count the same pair twice and don't pair a number with itself.
We start with ans = -1
to handle the case where no valid pairs exist. As we find valid pairs (those with matching largest digits), we update ans
only when we find a larger sum. This way, we're guaranteed to end up with either the maximum sum or -1 if no valid pairs were found.
The beauty of this approach lies in its simplicity - we're directly implementing what the problem asks for without any complex data structures or algorithms.
Solution Approach
The solution uses a brute force enumeration approach to check all possible pairs in the array.
We start by initializing ans = -1
to handle the case where no valid pair exists.
The implementation uses two nested loops to generate all pairs:
- The outer loop iterates through each element with its index:
for i, x in enumerate(nums)
- The inner loop iterates through all elements after position
i
:for y in nums[i + 1:]
This ensures we check each unique pair exactly once without duplicates.
For each pair (x, y)
:
- Calculate the sum:
v = x + y
- Check if this sum is greater than our current answer:
ans < v
- Check if both numbers have the same largest digit:
max(str(x)) == max(str(y))
- Converting to string allows us to easily access individual digits
- The
max()
function on a string returns the character with the highest ASCII value, which for digit characters corresponds to the largest digit
If both conditions are met (the sum is larger than our current best AND the largest digits match), we update our answer: ans = v
After checking all pairs, we return ans
, which will either be:
- The maximum sum of a valid pair, or
-1
if no pair with matching largest digits was found
The time complexity is O(n² × d)
where n
is the length of the array and d
is the average number of digits in the numbers (for the string conversion and max digit finding). The space complexity is O(d)
for the string conversions.
Ready to land your dream job?
Unlock your dream job with a 5-minute evaluator for a personalized learning plan!
Start EvaluatorExample Walkthrough
Let's walk through the solution with nums = [84, 91, 18, 59, 27]
.
First, we initialize ans = -1
to handle the case where no valid pairs exist.
Now we'll check all possible pairs:
Pair (84, 91): i=0, x=84, y=91
- Sum: v = 84 + 91 = 175
- Is 175 > -1? Yes
- Largest digit of 84: max("84") = '8'
- Largest digit of 91: max("91") = '9'
- Do they match? No (8 ≠ 9)
- Don't update ans
Pair (84, 18): i=0, x=84, y=18
- Sum: v = 84 + 18 = 102
- Is 102 > -1? Yes
- Largest digit of 84: max("84") = '8'
- Largest digit of 18: max("18") = '8'
- Do they match? Yes (8 = 8)
- Update ans = 102
Pair (84, 59): i=0, x=84, y=59
- Sum: v = 84 + 59 = 143
- Is 143 > 102? Yes
- Largest digit of 84: max("84") = '8'
- Largest digit of 59: max("59") = '9'
- Do they match? No (8 ≠ 9)
- Don't update ans
Pair (84, 27): i=0, x=84, y=27
- Sum: v = 84 + 27 = 111
- Is 111 > 102? Yes
- Largest digit of 84: max("84") = '8'
- Largest digit of 27: max("27") = '7'
- Do they match? No (8 ≠ 7)
- Don't update ans
Pair (91, 18): i=1, x=91, y=18
- Sum: v = 91 + 18 = 109
- Is 109 > 102? Yes
- Largest digit of 91: max("91") = '9'
- Largest digit of 18: max("18") = '8'
- Do they match? No (9 ≠ 8)
- Don't update ans
Pair (91, 59): i=1, x=91, y=59
- Sum: v = 91 + 59 = 150
- Is 150 > 102? Yes
- Largest digit of 91: max("91") = '9'
- Largest digit of 59: max("59") = '9'
- Do they match? Yes (9 = 9)
- Update ans = 150
Pair (91, 27): i=1, x=91, y=27
- Sum: v = 91 + 27 = 118
- Is 118 > 150? No
- Skip checking (sum not greater than current ans)
Pair (18, 59): i=2, x=18, y=59
- Sum: v = 18 + 59 = 77
- Is 77 > 150? No
- Skip checking
Pair (18, 27): i=2, x=18, y=27
- Sum: v = 18 + 27 = 45
- Is 45 > 150? No
- Skip checking
Pair (59, 27): i=3, x=59, y=27
- Sum: v = 59 + 27 = 86
- Is 86 > 150? No
- Skip checking
After checking all pairs, we return ans = 150
, which is the maximum sum of a pair where both numbers have the same largest digit (91 and 59, both with largest digit 9).
Solution Implementation
1class Solution:
2 def maxSum(self, nums: List[int]) -> int:
3 # Initialize the maximum sum to -1 (indicates no valid pair found)
4 max_sum = -1
5
6 # Iterate through each number with its index
7 for i, first_num in enumerate(nums):
8 # Compare with all numbers after the current index to avoid duplicate pairs
9 for second_num in nums[i + 1:]:
10 # Calculate the sum of the current pair
11 current_sum = first_num + second_num
12
13 # Check if this sum is better than our current maximum
14 # and if both numbers have the same maximum digit
15 if current_sum > max_sum and max(str(first_num)) == max(str(second_num)):
16 max_sum = current_sum
17
18 # Return the maximum sum found, or -1 if no valid pair exists
19 return max_sum
20
1class Solution {
2 /**
3 * Finds the maximum sum of two numbers from the array where both numbers
4 * have the same maximum digit.
5 *
6 * @param nums the input array of positive integers
7 * @return the maximum sum of two numbers with the same max digit, or -1 if no such pair exists
8 */
9 public int maxSum(int[] nums) {
10 int maxSumValue = -1;
11 int arrayLength = nums.length;
12
13 // Check all pairs of numbers in the array
14 for (int i = 0; i < arrayLength; ++i) {
15 for (int j = i + 1; j < arrayLength; ++j) {
16 int currentSum = nums[i] + nums[j];
17
18 // Update max sum if current sum is larger and both numbers have the same max digit
19 if (currentSum > maxSumValue && f(nums[i]) == f(nums[j])) {
20 maxSumValue = currentSum;
21 }
22 }
23 }
24
25 return maxSumValue;
26 }
27
28 /**
29 * Finds the maximum digit in a given positive integer.
30 *
31 * @param x the positive integer to process
32 * @return the maximum digit found in the number
33 */
34 private int f(int x) {
35 int maxDigit = 0;
36
37 // Extract each digit and track the maximum
38 while (x > 0) {
39 maxDigit = Math.max(maxDigit, x % 10);
40 x /= 10;
41 }
42
43 return maxDigit;
44 }
45}
46
1class Solution {
2public:
3 int maxSum(vector<int>& nums) {
4 int maxPairSum = -1; // Initialize result to -1 (no valid pair found)
5 int arraySize = nums.size();
6
7 // Lambda function to find the maximum digit in a number
8 auto findMaxDigit = [](int number) {
9 int maxDigit = 0;
10 // Extract digits by repeatedly dividing by 10
11 while (number > 0) {
12 maxDigit = max(maxDigit, number % 10); // Compare current digit with max
13 number /= 10; // Move to next digit
14 }
15 return maxDigit;
16 };
17
18 // Check all possible pairs in the array
19 for (int i = 0; i < arraySize; ++i) {
20 for (int j = i + 1; j < arraySize; ++j) {
21 int currentSum = nums[i] + nums[j];
22
23 // Update maxPairSum if:
24 // 1. Current sum is greater than maxPairSum
25 // 2. Both numbers have the same maximum digit
26 if (currentSum > maxPairSum &&
27 findMaxDigit(nums[i]) == findMaxDigit(nums[j])) {
28 maxPairSum = currentSum;
29 }
30 }
31 }
32
33 return maxPairSum; // Return the maximum sum found, or -1 if no valid pair exists
34 }
35};
36
1/**
2 * Finds the maximum sum of two numbers in the array that have the same maximum digit
3 * @param nums - Array of positive integers
4 * @returns Maximum sum of two numbers with same max digit, or -1 if no such pair exists
5 */
6function maxSum(nums: number[]): number {
7 const n: number = nums.length;
8 let maxSumResult: number = -1;
9
10 /**
11 * Extracts the maximum digit from a given number
12 * @param num - The input number
13 * @returns The maximum digit in the number
14 */
15 const getMaxDigit = (num: number): number => {
16 let maxDigit: number = 0;
17
18 // Iterate through each digit by repeatedly dividing by 10
19 while (num > 0) {
20 // Get the last digit using modulo operation
21 const currentDigit: number = num % 10;
22 // Update maximum digit if current digit is larger
23 maxDigit = Math.max(maxDigit, currentDigit);
24 // Remove the last digit by integer division
25 num = Math.floor(num / 10);
26 }
27
28 return maxDigit;
29 };
30
31 // Check all pairs of numbers in the array
32 for (let i: number = 0; i < n; ++i) {
33 for (let j: number = i + 1; j < n; ++j) {
34 // Calculate the sum of current pair
35 const currentSum: number = nums[i] + nums[j];
36
37 // Check if both numbers have the same maximum digit
38 // and if their sum is greater than current maximum
39 if (currentSum > maxSumResult && getMaxDigit(nums[i]) === getMaxDigit(nums[j])) {
40 maxSumResult = currentSum;
41 }
42 }
43 }
44
45 return maxSumResult;
46}
47
Time and Space Complexity
Time Complexity: O(n^2 × log M)
, where n
is the length of the array and M
is the maximum value in the array.
The analysis breaks down as follows:
- The outer loop iterates through all elements:
O(n)
- The inner loop iterates through remaining elements after index
i
:O(n)
in worst case - For each pair of numbers
(x, y)
, we computemax(str(x))
andmax(str(y))
:- Converting a number to string takes
O(log M)
time whereM
is the value of the number (number of digits is proportional tolog M
) - Finding the maximum character in the string also takes
O(log M)
time
- Converting a number to string takes
- Therefore, the total time complexity is
O(n × n × log M) = O(n^2 × log M)
Space Complexity: O(log M)
, where M
is the maximum value in the array.
The space analysis:
- The variable
ans
usesO(1)
space - The loop variables
i
,x
,y
, andv
useO(1)
space - The string conversion
str(x)
andstr(y)
create temporary strings of lengthO(log M)
- No additional data structures are used
- Therefore, the total space complexity is
O(log M)
Learn more about how to find time and space complexity quickly.
Common Pitfalls
1. Inefficient Repeated Digit Extraction
The current solution converts numbers to strings and finds the maximum digit for every pair comparison. This means if a number appears in multiple pairs, we're recalculating its maximum digit repeatedly.
Problem Example:
For an array like [51, 71, 17, 42, 51, 61]
, the number 51's maximum digit is calculated multiple times when it's paired with different numbers.
Solution: Pre-compute and cache the maximum digit for each number before checking pairs:
class Solution:
def maxSum(self, nums: List[int]) -> int:
# Pre-compute maximum digit for each number
max_digits = {}
for num in nums:
max_digits[num] = max(str(num))
max_sum = -1
for i, first_num in enumerate(nums):
for second_num in nums[i + 1:]:
current_sum = first_num + second_num
# Use cached values instead of recalculating
if current_sum > max_sum and max_digits[first_num] == max_digits[second_num]:
max_sum = current_sum
return max_sum
2. Suboptimal Algorithm for Large Arrays
The O(n²) approach becomes inefficient for large arrays when many numbers share the same maximum digit.
Problem Example: If most numbers have maximum digit 9, we're checking many unnecessary pairs and keeping only the maximum sum.
Optimized Solution: Group numbers by their maximum digit and only find the two largest numbers in each group:
class Solution:
def maxSum(self, nums: List[int]) -> int:
# Group numbers by their maximum digit
digit_groups = {}
for num in nums:
max_digit = max(str(num))
if max_digit not in digit_groups:
digit_groups[max_digit] = []
digit_groups[max_digit].append(num)
max_sum = -1
# For each group, find the sum of two largest numbers
for group in digit_groups.values():
if len(group) >= 2:
group.sort(reverse=True)
max_sum = max(max_sum, group[0] + group[1])
return max_sum
This reduces time complexity to O(n log n) in the worst case (when all numbers have the same maximum digit and need sorting).
Which of the following array represent a max heap?
Recommended Readings
Coding Interview Patterns Your Personal Dijkstra's Algorithm to Landing Your Dream Job The goal of AlgoMonster is to help you get a job in the shortest amount of time possible in a data driven way We compiled datasets of tech interview problems and broke them down by patterns This way
Recursion Recursion is one of the most important concepts in computer science Simply speaking recursion is the process of a function calling itself Using a real life analogy imagine a scenario where you invite your friends to lunch https assets algo monster recursion jpg You first call Ben and ask
Runtime Overview When learning about algorithms and data structures you'll frequently encounter the term time complexity This concept is fundamental in computer science and offers insights into how long an algorithm takes to complete given a certain input size What is Time Complexity Time complexity represents the amount of time
Want a Structured Path to Master System Design Too? Don’t Miss This!