Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Largest number in given Array formed by repeatedly combining two same elements

  • Last Updated : 26 Nov, 2021

Given an array arr[], the task is to find the largest number in given Array, formed by repeatedly combining two same elements. If there are no same elements in the array initially, then print the output as -1.
Examples: 
 

Input: arr = {1, 1, 2, 4, 7, 8} 
Output: 16 
Explanation: 
Repetition 1: Combine 1s from the array and insert the sum 2 in it. Updated Array = {2, 2, 4, 7, 8} 
Repetition 2: Combine 2s from the array and insert the sum 4 in it. Updated Array = {4, 4, 7, 8} 
Repetition 3: Combine 4s from the array and insert the sum 8 in it. Updated Array = {8, 7, 8} 
Repetition 4: Combine 8s from the array and insert the sum 16 in it. Updated Array = {7, 16} 
Largest sum = 16
Input: arr = {1, 2, 3} 
Output: -1 
Explanation: 
There are no duplicate elements in the array initially. Hence no combination can be performed. 
 

Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

 

Approach: This problem can be solved using the frequency of elements in the given array.
 



  • Find and store the frequencies of each element of the given array in a map.
  • Upon traversing the frequency map for each distinct element, if there is any duplicate element K in the map with a frequency more than 1, then increase the frequency of element 2*K by half the frequency of the K element. 
     
  • Finally, find the maximum number from the map.

Below is the implementation of the above approach: 
 

CPP




// C++ implementation of the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to return the largest sum
int largest_sum(int arr[], int n)
{
    // Variable to store the largest sum
    int maximum = -1;
 
    // Map to store the frequencies
    // of each element
    map<int, int> m;
 
    // Store the Frequencies
    for (int i = 0; i < n; i++) {
        m[arr[i]]++;
    }
 
    // Loop to combine duplicate elements
    // and update the sum in the map
    for (auto j : m) {
 
        // If j is a duplicate element
        if (j.second > 1) {
 
            // Update the frequency of 2*j
            m[2 * j.first]
                = m[2 * j.first]
                  + j.second / 2;
 
            // If the new sum is greater than
            // maximum value, Update the maximum
            if (2 * j.first > maximum)
                maximum = 2 * j.first;
        }
    }
 
    // Returns the largest sum
    return maximum;
}
 
// Driver Code
int main()
{
    int arr[] = { 1, 1, 2, 4, 7, 8 };
    int n = sizeof(arr)
            / sizeof(arr[0]);
 
    // Function Calling
    cout << largest_sum(arr, n);
 
    return 0;
}

Java




// Java implementation of the above approach
import java.util.*;
 
class GFG {
 
     
    // Function to return the largest sum
    static int largest_sum(int arr[], int n)
    {
        // Variable to store the largest sum
        int maximum = -1;
     
        // Map to store the frequencies
        // of each element
        HashMap<Integer, Integer> m = new HashMap<Integer, Integer>();
     
        // Store the Frequencies
        for (int i = 0; i < n; i++) {
             
            if (m.containsKey(arr[i])){
            m.put(arr[i], m.get(arr[i]) + 1);
            }
            else{
                m.put(arr[i], 1);
            }
        }
     
        // Loop to combine duplicate elements
        // and update the sum in the map
        for(int i = 0; i < n; i++){
 
            // If j is a duplicate element
            if (m.get(arr[i]) > 1) {
                 
                if (m.containsKey(2*arr[i]))
                {
                    // Update the frequency of 2*j
                    m.put(2*arr[i],m.get(2 * arr[i])+ m.get(arr[i]) / 2);
                }
                else
                {
                    m.put(2*arr[i],m.get(arr[i]) / 2);
                }
                 
                // If the new sum is greater than
                // maximum value, Update the maximum
                if (2 * arr[i] > maximum)
                    maximum = 2 * arr[i];
            }
            }
     
        // Returns the largest sum
        return maximum;
    }
     
    // Driver Code
    public static void main (String[] args)
    {
        int arr[] = { 1, 1, 2, 4, 7, 8 };
        int n = arr.length;
         
        // Function Calling
        System.out.println(largest_sum(arr, n));
    }
}
 
// This code is contributed by Yash_R

Python3




# Python3 implementation of the above approach
 
# Function to return the largest sum
def largest_sum(arr, n):
     
    # Variable to store the largest sum
    maximum = -1
 
    # Map to store the frequencies
    # of each element
    m = dict()
 
    # Store the Frequencies
    for i in arr:
        m[i] = m.get(i,0) + 1
 
    # Loop to combine duplicate elements
    # and update the sum in the map
    for j in list(m):
 
        # If j is a duplicate element
        if ((j in m) and m[j] > 1):
 
            # Update the frequency of 2*j
            x, y = 0, 0
            if 2*j in m:
                m[2*j] = m[2 * j]+ m[j]// 2
            else:
                m[2*j] = m[j]//2
 
            # If the new sum is greater than
            # maximum value, Update the maximum
            if (2 * j > maximum):
                maximum = 2 * j
 
    # Returns the largest sum
    return maximum
 
# Driver Code
if __name__ == '__main__':
    arr= [1, 1, 2, 4, 7, 8]
    n = len(arr)
 
    # Function Calling
    print(largest_sum(arr, n))
 
# This code is contributed by mohit kumar 29   

C#




// C# implementation of the above approach
using System;
using System.Collections.Generic;
 
class GFG {
 
     
    // Function to return the largest sum
    static int largest_sum(int []arr, int n)
    {
        // Variable to store the largest sum
        int maximum = -1;
     
        // Map to store the frequencies
        // of each element
        Dictionary<int, int> m = new Dictionary<int, int>();
     
        // Store the Frequencies
        for (int i = 0; i < n; i++) {
             
            if (m.ContainsKey(arr[i])){
                m[arr[i]]++;
            }
            else{
                m.Add(arr[i] , 1);
            }
        }
     
        // Loop to combine duplicate elements
        // and update the sum in the map
        for(int i = 0; i < n; i++){
 
            // If j is a duplicate element
            //Console.Write(m[arr[i]]);
             
            if (m[arr[i]] > 1) {
                 
                if (m.ContainsKey(2*arr[i]))
                {
                    // Update the frequency of 2*j
                    m[2*arr[i]] = m[2 * arr[i]]+ m[arr[i]] / 2;
                }
                else
                {
                    m.Add(2*arr[i],m[arr[i]] / 2);
                }
                 
                // If the new sum is greater than
                // maximum value, Update the maximum
                if (2 * arr[i] > maximum)
                    maximum = 2 * arr[i];
            }
             
            }
     
        // Returns the largest sum
        return maximum;
    }
     
    // Driver Code
    public static void Main ()
    {
        int[] arr = { 1, 1, 2, 4, 7, 8 };
        int n = arr.Length;
         
        // Function Calling
        Console.Write(largest_sum(arr, n));
    }
}
 
// This code is contributed by chitranayal

Javascript




<script>
 
// Javascript implementation of the above approach
 
// Function to return the largest sum
    function largest_sum(arr, n)
    {
        // Variable to store the largest sum
        let maximum = -1;
       
        // Map to store the frequencies
        // of each element
        let m = new Map();
       
        // Store the Frequencies
        for (let i = 0; i < n; i++) {
               
            if (m.has(arr[i])){
            m.set(arr[i], m.get(arr[i]) + 1);
            }
            else{
                m.set(arr[i], 1);
            }
        }
       
        // Loop to combine duplicate elements
        // and update the sum in the map
        for(let i = 0; i < n; i++){
   
            // If j is a duplicate element
            if (m.get(arr[i]) > 1) {
                   
                if (m.has(2*arr[i]))
                {
                    // Update the frequency of 2*j
                    m.set(2*arr[i],m.get(2 * arr[i])+ m.get(arr[i]) / 2);
                }
                else
                {
                    m.set(2*arr[i],m.get(arr[i]) / 2);
                }
                   
                // If the new sum is greater than
                // maximum value, Update the maximum
                if (2 * arr[i] > maximum)
                    maximum = 2 * arr[i];
            }
            }
       
        // Returns the largest sum
        return maximum;
    }
       
// Driver code
     
          let arr = [ 1, 1, 2, 4, 7, 8 ];
        let n = arr.length;
           
        // Function Calling
        document.write(largest_sum(arr, n));
                                                                                 
</script>
Output: 
16

 

Time Complexity: O(n)

Auxiliary Space: O(n)




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!