Maximize the sum of selected numbers from an array to make it empty | Function to maximise the sum of selected numbers by deleting occurences of Ai - 1 and Ai + 1 ; Number of elements in the array ; Largest element in the array ; An array to count the occurence of each element ; ans to store the result ; Using the above mentioned approach ; if occurence is greater than 0 ; add it to ans ; decrease i - 1 th element by 1 ; decrease ith element by 1 ; decrease i ; Driver code
function getMaximumSum ( arr ) { let n = arr . length ; let max = Number . MIN_VALUE ; for ( let i = 0 ; i < n ; i ++ ) { max = Math . max ( max , arr [ i ] ) ; } let freq = new Array ( max + 1 ) ; freq . fill ( 0 ) ; for ( let j = 0 ; j < n ; j ++ ) { freq [ arr [ j ] ] ++ ; } let ans = 0 , i = max ; while ( i > 0 ) { if ( freq [ i ] > 0 ) { ans += i ; freq [ i - 1 ] -- ; freq [ i ] -- ; } else { i -- ; } } return ans ; } let a = [ 1 , 2 , 3 ] ; document . write ( getMaximumSum ( a ) ) ;