text: Largest number in given Array formed by repeatedly combining two same elements | 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: function largest_sum ( arr , n ) { let maximum = - 1 ; let m = new Map ( ) ; 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 ) ; } } for ( let i = 0 ; i < n ; i ++ ) { if ( m . get ( arr [ i ] ) > 1 ) { if ( m . has ( 2 * arr [ i ] ) ) { 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 ( 2 * arr [ i ] > maximum ) maximum = 2 * arr [ i ] ; } } return maximum ; } let arr = [ 1 , 1 , 2 , 4 , 7 , 8 ] ; let n = arr . length ; document . write ( largest_sum ( arr , n ) ) ;