-
Notifications
You must be signed in to change notification settings - Fork 6
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
2342. Max Sum of a Pair With Equal Sum of Digits #1306
Comments
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:
|
…m-of-digits submissions 1540563024 Co-authored-by: kovatz <[email protected]> Co-authored-by: topugit <[email protected]> Co-authored-by: basharul-siddike <[email protected]> Co-authored-by: hafijul233 <[email protected]>
Discussed in #1305
Originally posted by mah-shamim February 12, 2025
Topics:
Array
,Hash Table
,Sorting
,Heap (Priority Queue)
You are given a 0-indexed array
nums
consisting of positive integers. You can choose two indicesi
andj
, such thati != j
, and the sum of digits of the numbernums[i]
is equal to that ofnums[j]
.Return the maximum value of
nums[i] + nums[j]
that you can obtain over all possible indicesi
andj
that satisfy the conditions.Example 1:
So the maximum sum that we can obtain is 54.
Example 2:
Constraints:
1 <= nums.length <= 105
1 <= nums[i] <= 109
Hint:
The text was updated successfully, but these errors were encountered: