Minimum length of the reduced Array formed using given operations | Function to find the length of minimized array ; Creating the required dp t0ables Initialising the dp table by - 1 ; Initialising the dp table by - 1 ; base case ; Check if the two subarray can be combined ; Initialising dp1 table with max value ; Check if the subarray can be reduced to a single element ; Minimal partition of [ 1 : j - 1 ] + 1 ; Driver code
function minimalLength ( a , n ) { var i , j , k ; var dp = Array ( n + 1 ) . fill ( Array ( n + 1 ) . fill ( - 1 ) ) ; var dp1 = Array ( n ) . fill ( 0 ) ; for ( var size = 1 ; size <= n ; size ++ ) { for ( i = 0 ; i < n - size + 1 ; i ++ ) { j = i + size - 1 ; if ( i == j ) dp [ i ] [ j ] = a [ i ] ; else { for ( k = i ; k < j ; k ++ ) { if ( dp [ i ] [ k ] != - 1 && dp [ i ] [ k ] == dp [ k + 1 ] [ j ] ) dp [ i ] [ j ] = dp [ i ] [ k ] + 1 ; } } } } for ( i = 0 ; i < n ; i ++ ) dp1 [ i ] = 1000000000 ; for ( i = 0 ; i < n ; i ++ ) { for ( j = 0 ; j <= i ; j ++ ) { if ( dp [ j ] [ i ] != - 1 ) { if ( j == 0 ) dp1 [ i ] = 2 ; else dp1 [ i ] = Math . min ( dp1 [ i ] , dp1 [ j - 1 ] + 1 ) ; } } } return dp1 [ n - 1 ] ; } var n = 7 ; var a = [ 3 , 3 , 4 , 4 , 4 , 3 , 3 ] ; document . write ( minimalLength ( a , n ) ) ;