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