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 Console . Write ( m [ arr [ i ] ] ) ; ; 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: using System ; using System . Collections . Generic ; class GFG { static int largest_sum ( int [ ] arr , int n ) { int maximum = - 1 ; Dictionary < int , int > m = new Dictionary < int , int > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( m . ContainsKey ( arr [ i ] ) ) { m [ arr [ i ] ] ++ ; } else { m . Add ( arr [ i ] , 1 ) ; } } for ( int i = 0 ; i < n ; i ++ ) { if ( m [ arr [ i ] ] > 1 ) { if ( m . ContainsKey ( 2 * arr [ i ] ) ) { m [ 2 * arr [ i ] ] = m [ 2 * arr [ i ] ] + m [ arr [ i ] ] / 2 ; } else { m . Add ( 2 * arr [ i ] , m [ arr [ i ] ] / 2 ) ; } if ( 2 * arr [ i ] > maximum ) maximum = 2 * arr [ i ] ; } } return maximum ; } public static void Main ( ) { int [ ] arr = { 1 , 1 , 2 , 4 , 7 , 8 } ; int n = arr . Length ; Console . Write ( largest_sum ( arr , n ) ) ; } }