Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Find maximum sum pair with same digit sum

  • Difficulty Level : Medium
  • Last Updated : 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 101
Explanation: 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:

  1. 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.
  2. Now create a global variable ans to store the answer to this problem.
  3. 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.
  4. Return ans as the answer to this problem.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find sum of digits
int 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 digits
void 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




// Java program for the above approach
import java.util.*;
 
class GFG{
 
// Function to find sum of digits
static 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 digits
static 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

Python3




# Python Program to implement
# the above approach
 
# Function to find sum of digits
def 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 digits
def 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#




// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG{
 
// Function to find sum of digits
static 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 digits
static 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

Javascript




<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>
Output
46 55 101

Time complexity: O(N)
Auxiliary Space: O(N)


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!