Find maximum sum pair with same digit sum - GeeksforGeeks

15 Dec, 2021
Given an array arr having N integers, the task is to find a pair with maximum sum and having the same sum of digits. Print the sum of that pair, if it exists. Otherwise, print -1.
Examples: 
Input:  arr[]={55, 23, 32, 46, 88}Output:  46 55 101Explanation: Pair {55, 46} will give the sum of 55 + 46 = 101 
Input: arr[]={18, 19, 23, 15}Output: -1
Approach: Follow the below steps to solve this problem:
Create a map, say mp to store the sum of digits in a number as the key and the maximum number having that sum of digits as the value.Now create a global variable ans to store the answer to this problem.Now start traversing the array, and in each iteration:Check if the sum of its digit is already present in the map. If it is, then change ans with the maximum of ans and the sum of the two numbers.If the sum of the digits is not present in the map. Create a new key for it and store its value. Otherwise, update the number in the map if it’s greater than the existing number.Return ans as the answer to this problem.
Create a map, say mp to store the sum of digits in a number as the key and the maximum number having that sum of digits as the value.
Now create a global variable ans to store the answer to this problem.
Now start traversing the array, and in each iteration:Check if the sum of its digit is already present in the map. If it is, then change ans with the maximum of ans and the sum of the two numbers.If the sum of the digits is not present in the map. Create a new key for it and store its value. Otherwise, update the number in the map if it’s greater than the existing number.
Check if the sum of its digit is already present in the map. If it is, then change ans with the maximum of ans and the sum of the two numbers.
If the sum of the digits is not present in the map. Create a new key for it and store its value. Otherwise, update the number in the map if it’s greater than the existing number.
Return ans as the answer to this problem.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to find sum of digitsint digitSum(long n){    long sum = 0;    while (n) {        sum += (n % 10);        n /= 10;    }    return sum;} // Function to find maximum sum pair// having the same sum of digitsvoid findMax(vector<int> arr, int n){    // Map to store the sum of digits    // in a number as the key and    // the maximum number having    // that sum of digits as the value    unordered_map<int, int> mp;    int ans = -1, pairi = 0, pairj = 0;    for (int i = 0; i < n; i++) {         // Store the current sum of digits        // of the number in temp        int temp = digitSum(arr[i]);         // If temp is already present        // in the map then update        // ans if the sum is greater        // than the existing value        if (mp[temp] != 0) {            if (arr[i] + mp[temp] > ans) {                pairi = arr[i];                pairj = mp[temp];                ans = pairi + pairj;            }        }         // Change the value in the map        mp[temp] = max(arr[i], mp[temp]);    }     cout << pairi << " " << pairj         << " " << ans << endl;} // Driver Code Starts.int main(){    vector<int> arr = { 55, 23, 32, 46, 88 };    int n = arr.size();    findMax(arr, n);    return 0;}
// Java program for the above approachimport java.util.*; class GFG{ // Function to find sum of digitsstatic int digitSum(long n){    int sum = 0;    while (n > 0)    {        sum += (n % 10);        n /= 10;    }    return sum;} // Function to find maximum sum pair// having the same sum of digitsstatic void findMax(int []arr, int n){       // Map to store the sum of digits    // in a number as the key and    // the maximum number having    // that sum of digits as the value    HashMap<Integer,Integer> mp = new HashMap<Integer,Integer>();    int ans = -1, pairi = 0, pairj = 0;    for (int i = 0; i < n; i++) {         // Store the current sum of digits        // of the number in temp        int temp = digitSum(arr[i]);         // If temp is already present        // in the map then update        // ans if the sum is greater        // than the existing value        if (mp.containsKey(temp)) {            if (arr[i] + mp.get(temp) > ans) {                pairi = arr[i];                pairj = mp.get(temp);                ans = pairi + pairj;            }            mp.put(temp, Math.max(arr[i], mp.get(temp)));        }        else        // Change the value in the map        mp.put(temp, arr[i]);             }     System.out.print(pairi+ " " +  pairj        + " " +  ans +"\n");} // Driver Code Starts.public static void main(String[] args){    int []arr = { 55, 23, 32, 46, 88 };    int n = arr.length;    findMax(arr, n);}} // This code is contributed by shikhasingrajput
# Python Program to implement# the above approach # Function to find sum of digitsdef digitSum(n):    sum = 0    while (n):        sum += (n % 10)        n = n // 10    return sum # Function to find maximum sum pair# having the same sum of digitsdef findMax(arr, n):     # Map to store the sum of digits    # in a number as the key and    # the maximum number having    # that sum of digits as the value    mp = {}    ans = -1    pairi = 0    pairj = 0    for i in range(n):         # Store the current sum of digits        # of the number in temp        temp = digitSum(arr[i])         # If temp is already present        # in the map then update        # ans if the sum is greater        # than the existing value        if (temp not in mp):            mp[temp] = 0                 if (mp[temp] != 0) :            if (arr[i] + mp[temp] > ans):                pairi = arr[i]                pairj = mp.get(temp)                ans = pairi + pairj                     # Change the value in the map        mp[temp] = max(arr[i], mp[temp])    print(f"{pairi} {pairj} {ans}") # Driver Code Starts.arr = [55, 23, 32, 46, 88]n = len(arr)findMax(arr, n) # This code is contributed by Saurabh Jaiswal
// C# program for the above approachusing System;using System.Collections.Generic; class GFG{ // Function to find sum of digitsstatic int digitSum(long n){    int sum = 0;    while (n > 0)    {        sum += (int)(n % 10);        n /= 10;    }    return sum;} // Function to find maximum sum pair// having the same sum of digitsstatic void findMax(int []arr, int n){       // Map to store the sum of digits    // in a number as the key and    // the maximum number having    // that sum of digits as the value    Dictionary<int,int> mp = new Dictionary<int, int>();    int ans = -1, pairi = 0, pairj = 0;    for (int i = 0; i < n; i++) {         // Store the current sum of digits        // of the number in temp        int temp = digitSum(arr[i]);         // If temp is already present        // in the map then update        // ans if the sum is greater        // than the existing value        if (mp.ContainsKey(temp)) {            if (arr[i] + mp[temp] > ans) {                pairi = arr[i];                pairj = mp[temp];                ans = pairi + pairj;            }            mp[temp] = Math.Max(arr[i], mp[temp]);        }        else        // Change the value in the map        mp[temp] = arr[i];             }     Console.WriteLine(pairi+ " " +  pairj + " " +  ans );} // Driver Code Starts.public static void Main(){    int []arr = { 55, 23, 32, 46, 88 };    int n = arr.Length;    findMax(arr, n);}} // This code is contributed by Saurabh Jaiswal
<script>        // JavaScript Program to implement       // the above approach        // Function to find sum of digits       function digitSum(n) {           let sum = 0;           while (n) {               sum += (n % 10);               n = Math.floor(n / 10);           }           return sum;       }        // Function to find maximum sum pair       // having the same sum of digits       function findMax(arr, n)       {                   // Map to store the sum of digits           // in a number as the key and           // the maximum number having           // that sum of digits as the value           let mp = new Map();           let ans = -1, pairi = 0, pairj = 0;           for (let i = 0; i < n; i++) {                // Store the current sum of digits               // of the number in temp               let temp = digitSum(arr[i]);                // If temp is already present               // in the map then update               // ans if the sum is greater               // than the existing value                if (!mp.has(temp)) {                   mp.set(temp, 0);               }               if (mp.get(temp) != 0) {                   if (arr[i] + mp.get(temp) > ans) {                       pairi = arr[i];                       pairj = mp.get(temp);                       ans = pairi + pairj;                   }               }                // Change the value in the map               mp.set(temp, Math.max(arr[i], mp.get(temp)));           }            document.write(pairi + " " + pairj               + " " + ans + '<br>');       }        // Driver Code Starts.       let arr = [55, 23, 32, 46, 88];       let n = arr.length;       findMax(arr, n);    // This code is contributed by Potta Lokesh   </script>
46 55 101
Time complexity: O(N)Auxiliary Space: O(N)
lokeshpotta20
_saurabh_jaiswal
anikakapoor
shikhasingrajput
number-digits
Arrays
Mathematical
Arrays
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Window Sliding Technique
Trapping Rain Water
Reversal algorithm for array rotation
Move all negative numbers to beginning and positive to end with constant extra space
Program to find sum of elements in a given array
Program for Fibonacci numbers
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7