Split array into subarrays at minimum cost by minimizing count of repeating elements in each subarray | Function to find the minimum cost of splitting the array into subarrays ; Size of the array ; Get the maximum element ; dp [ ] will store the minimum cost upto index i ; Initialise the first element ; Create the frequency array ; Update the frequency ; Counting the cost of the duplicate element ; Minimum cost of operation from 0 to j ; Total cost of the array ; Driver Code ; Given cost K ; Function Call
function findMinCost ( a , k ) { var n = a . length ; var max_ele = a . reduce ( ( a , b ) => Math . max ( a , b ) ) var dp = Array ( n + 1 ) . fill ( 1000000000 ) ; dp [ 0 ] = 0 ; for ( var i = 0 ; i < n ; ++ i ) { var freq = Array ( max_ele + 1 ) . fill ( 0 ) ; for ( var j = i ; j < n ; ++ j ) { freq [ a [ j ] ] ++ ; var cost = 0 ; for ( var x = 0 ; x <= max_ele ; ++ x ) { cost += ( freq [ x ] == 1 ) ? 0 : freq [ x ] ; } dp [ j + 1 ] = Math . min ( dp [ i ] + cost + k , dp [ j + 1 ] ) ; } } return dp [ n ] ; } var arr = [ 1 , 2 , 1 , 1 , 1 ] ; var K = 2 ; document . write ( findMinCost ( arr , K ) ) ;