Maximum modified Array sum possible by choosing elements as per the given conditions | Function that finds the maximum sum of the array elements according to the given condition ; Sort the array ; Take the max value from the array ; Iterate from the end of the array ; Check for the number had come before or not ; Take the value which is not occured already ; Change max to new value ; Return the maximum sum ; Given array arr [ ] ; Function Call
function findMaxValue ( arr , n ) { arr . sort ( ( a , b ) => a - b ) ; let ans = arr [ n - 1 ] ; let maxPossible = arr [ n - 1 ] ; for ( let i = n - 2 ; i >= 0 ; -- i ) { if ( maxPossible > 0 ) { if ( arr [ i ] >= maxPossible ) { ans += ( maxPossible - 1 ) ; maxPossible = maxPossible - 1 ; } else { maxPossible = arr [ i ] ; ans += maxPossible ; } } } return ans ; } let arr = [ 4 , 4 , 1 , 5 ] ; let n = arr . length ; document . write ( findMaxValue ( arr , n ) ) ;