Largest number in given Array formed by repeatedly combining two same elements | Java 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
import java . util . * ; class GFG { static int largest_sum ( int arr [ ] , int n ) { int maximum = - 1 ; HashMap < Integer , Integer > m = new HashMap < Integer , Integer > ( ) ; 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 ) ; } } for ( int i = 0 ; i < n ; i ++ ) { if ( m . get ( arr [ i ] ) > 1 ) { if ( m . containsKey ( 2 * arr [ i ] ) ) { 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 ( 2 * arr [ i ] > maximum ) maximum = 2 * arr [ i ] ; } } return maximum ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 1 , 2 , 4 , 7 , 8 } ; int n = arr . length ; System . out . println ( largest_sum ( arr , n ) ) ; } }