Find maximum points which can be obtained by deleting elements from array | Java program to find maximum cost after deleting all the elements form the array ; function to return maximum cost obtained ; find maximum element of the array . ; initialize count of all elements to zero . ; calculate frequency of all elements of array . ; stores cost of deleted elements . ; selecting minimum range from L and R . ; finds upto which elements are to be deleted when element num is selected . ; get maximum when selecting element num or not . ; Driver program ; size of array ; function call to find maximum cost
public class GFG { static int maxCost ( int a [ ] , int n , int l , int r ) { int mx = 0 , k ; for ( int i = 0 ; i < n ; ++ i ) mx = Math . max ( mx , a [ i ] ) ; int [ ] count = new int [ mx + 1 ] ; for ( int i = 0 ; i < count . length ; i ++ ) count [ i ] = 0 ; for ( int i = 0 ; i < n ; i ++ ) count [ a [ i ] ] ++ ; int [ ] res = new int [ mx + 1 ] ; res [ 0 ] = 0 ; l = Math . min ( l , r ) ; for ( int num = 1 ; num <= mx ; num ++ ) { k = Math . max ( num - l - 1 , 0 ) ; res [ num ] = Math . max ( res [ num - 1 ] , num * count [ num ] + res [ k ] ) ; } return res [ mx ] ; } public static void main ( String [ ] args ) { int a [ ] = { 2 , 1 , 2 , 3 , 2 , 2 , 1 } , l = 1 , r = 1 ; int n = a . length ; System . out . println ( maxCost ( a , n , l , r ) ) ; } }