Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Hash
  • Practice Hash
  • MCQs on Hash
  • Hashing Tutorial
  • Hash Function
  • Index Mapping
  • Collision Resolution
  • Open Addressing
  • Separate Chaining
  • Quadratic probing
  • Double Hashing
  • Load Factor and Rehashing
  • Advantage & Disadvantage
Open In App
Next Article:
Longest increasing sub-sequence formed by concatenating array to itself N times
Next article icon

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

Last Updated : 26 Nov, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

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. 
 

 

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)



Next Article
Longest increasing sub-sequence formed by concatenating array to itself N times

P

PratikLath
Improve
Article Tags :
  • Arrays
  • DSA
  • Hash
  • Mathematical
  • array-rearrange
Practice Tags :
  • Arrays
  • Hash
  • Mathematical

Similar Reads

  • Find the largest element in an array generated using the given conditions
    Given an integer N (2 ? N ? 1e6), the task is to find the maximum element present in the array arr[] of size N + 1 generated based on the following steps: arr[0] = 0arr[1] = 1arr[2 * i] = arr[i], when 2 ? 2 * i ? Narr[2 * i + 1] = Arr[i] + Arr[i + 1] when 2 ? 2 * i + 1 ? N Examples: Input: N = 7 Out
    7 min read
  • Find the largest Number that can be formed with the given Digits
    Given an array of integers arr[] represents digits of a number. The task is to write a program to generate the largest number possible using these digits. Note: The digits in the array are between 0 and 9. That is, 0 < arr[i] < 9. Examples: Input: arr[] = {4, 7, 9, 2, 3}Output: Largest number:
    10 min read
  • Maximize count of corresponding same elements in given Arrays by Rotation
    Given two arrays arr1[] and arr2[] of N integers and array arr1[] has distinct elements. The task is to find the maximum count of corresponding same elements in the given arrays by performing cyclic left or right shift on array arr1[]. Examples: Input: arr1[] = { 6, 7, 3, 9, 5 }, arr2[] = { 7, 3, 9,
    8 min read
  • Javascript Program to Maximize count of corresponding same elements in given Arrays by Rotation
    Given two arrays arr1[] and arr2[] of N integers and array arr1[] has distinct elements. The task is to find the maximum count of corresponding same elements in the given arrays by performing cyclic left or right shift on array arr1[]. Examples: Input: arr1[] = { 6, 7, 3, 9, 5 }, arr2[] = { 7, 3, 9,
    3 min read
  • Longest increasing sub-sequence formed by concatenating array to itself N times
    Given an array arr[] of size N, the task is to find the length of the longest increasing subsequence in the array formed by the concatenation of the arr[] to itself at the end N times.Examples: Input: arr[] = {3, 2, 1}, N = 3 Output: 3 Explanation: The array formed by the concatenation - {3, 2, 1, 3
    5 min read
  • Largest element in the array that is repeated exactly k times
    Given an array of integers and an integer 'k', the task is to find the largest element from the array that is repeated exactly 'k' times. Examples: Input: arr = {1, 1, 2, 3, 3, 4, 5, 5, 6, 6, 6}, k = 2 Output: 5 The elements that exactly occur 2 times are 1, 3 and 5 And, the largest element among th
    15 min read
  • Count elements of same value placed at same indices of two given arrays
    Given two arrays A[] and B[] of N unique elements, the task is to find the maximum number of matched elements from the two given arrays. Elements of the two arrays are matched if they are of the same value and can be placed at the same index (0-based indexing).(By right shift or left shift of the tw
    8 min read
  • Maximum number of contiguous array elements with same number of set bits
    Given an array with n elements. The task is to find the maximum number of contiguous array elements which have the same number of set bits. Examples: Input : arr[] = {14, 1, 2, 32, 12, 10} Output : 3 Elements 1, 2, 32 have same number of set bits and are contiguous. Input : arr[] = {1, 6, 9, 15, 8}
    6 min read
  • Maximize count of distinct elements possible in an Array from the given operation
    Given an array A[] of size N, the task is to maximize the count of distinct elements in the array by inserting the absolute differences of the existing array elements. Examples: Input: A[] = {1, 2, 3, 5} Output: 5 Explanation: Possible absolute differences among the array elements are: (2 - 1) = 1 (
    6 min read
  • Longest Subarray consisting of unique elements from an Array
    Given an array arr[] consisting of N integers, the task is to find the largest subarray consisting of unique elements only. Examples: Input: arr[] = {1, 2, 3, 4, 5, 1, 2, 3} Output: 5 Explanation: One possible subarray is {1, 2, 3, 4, 5}. Input: arr[]={1, 2, 4, 4, 5, 6, 7, 8, 3, 4, 5, 3, 3, 4, 5, 6,
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences