Maximize sum of given array by rearranging array such that the difference between adjacent elements is atmost 1 | Function to find maximum possible sum after changing the array elements as per the given constraints ; Stores the frequency of elements in given array ; Update frequency ; Stores the previously selected integer ; Stores the maximum possible sum ; Traverse over array count [ ] ; Run loop for each k ; Update ans ; Return maximum possible sum ; Given array arr [ ] ; Size of array ; Function Call
function maxSum ( a , n ) { var count = Array ( n + 1 ) . fill ( 0 ) ; for ( var i = 0 ; i < n ; i ++ ) count [ Math . min ( a [ i ] , n ) ] ++ ; var size = 0 ; var ans = 0 ; for ( var k = 1 ; k <= n ; k ++ ) { while ( count [ k ] > 0 && size < k ) { size ++ ; ans += size ; count [ k ] -- ; } ans += k * count [ k ] ; } return ans ; } var arr = [ 3 , 5 , 1 ] ; var n = arr . length ; document . write ( maxSum ( arr , n ) ) ;