Maximum modified Array sum possible by choosing elements as per the given conditions | Java program for the above approach ; 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 ; Driver Code ; Given array arr [ ] ; Function Call
import java . util . * ; class GFG { static int findMaxValue ( int arr [ ] , int n ) { Arrays . sort ( arr ) ; int ans = arr [ n - 1 ] ; int maxPossible = arr [ n - 1 ] ; for ( int 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 ; } public static void main ( String [ ] args ) { int arr [ ] = { 4 , 4 , 1 , 5 } ; int n = arr . length ; System . out . print ( findMaxValue ( arr , n ) ) ; } }