2342. Max Sum of a Pair With Equal Sum of Digits #1305
-
Topics: You are given a 0-indexed array Return the maximum value of Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
The approach can be divided into several steps:
Let's implement this solution in PHP: 2342. Max Sum of a Pair With Equal Sum of Digits <?php
/**
* @param Integer[] $nums
* @return Integer
*/
function maximumSum($nums) {
// Hash table to group numbers by their sum of digits
$digitSumMap = [];
// Fill the hash table with numbers grouped by their sum of digits
foreach ($nums as $num) {
$sum = $this->sumOfDigits($num);
if (!isset($digitSumMap[$sum])) {
$digitSumMap[$sum] = [];
}
// Add the number to the corresponding group
$digitSumMap[$sum][] = $num;
}
$maxSum = -1;
// For each group of numbers with the same sum of digits
foreach ($digitSumMap as $numbers) {
// Sort the group in descending order
rsort($numbers);
// If there are at least two numbers, calculate the sum of the largest two
if (count($numbers) > 1) {
$currentSum = $numbers[0] + $numbers[1];
// Update maxSum if we found a larger sum
$maxSum = max($maxSum, $currentSum);
}
}
return $maxSum;
}
/**
* Helper function to calculate the sum of digits of a number
*
* @param $num
* @return int
*/
function sumOfDigits($num) {
$sum = 0;
while ($num > 0) {
$sum += $num % 10;
$num = (int)($num / 10);
}
return $sum;
}
// Example usage
$nums1 = [18, 43, 36, 13, 7];
$nums2 = [10, 12, 19, 14];
echo maxSum($nums1); // Output: 54
echo "\n";
echo maxSum($nums2); // Output: -1
?> Explanation:
Time Complexity:
Space Complexity:
|
Beta Was this translation helpful? Give feedback.
The approach can be divided into several steps:
Group the numbers by their sum of digits.
For each group, find the two largest numbers.
Return the maximum sum.
Let's implement this solution in PHP: 2342. Max Sum of a Pair With Equal Sum of Digits