Construct the largest number whose sum of cost of digits is K | Function to find the maximum number among the two numbers S and T ; If "0" exists in the string S ; If "0" exists in the string T ; Else return the maximum number formed ; Recursive function to find maximum number formed such that the sum of cost of digits of formed number is K ; Base Case ; Return the stored state ; Including the digit ( idx + 1 ) ; Excluding the digit ( idx + 1 ) ; Store the result and return ; Function to find the maximum number formed such that the sum of the cost digits in the formed number is K ; Stores all Dp - states ; Recursive Call ; Return the result ; Driver Code
function getMaximum ( S , T ) { if ( S . indexOf ( " " ) > - 1 ) return T ; if ( T . indexOf ( " " ) > - 1 ) return S ; return S . length > T . length ? S : T ; } function recursion ( arr , idx , N , K , dp ) { if ( K == 0 ) { return " " ; } if ( K < 0 idx == N ) { return " " ; } if ( dp [ idx ] [ K ] != " " ) return dp [ idx ] [ K ] ; let include = String ( idx + 1 ) + recursion ( arr , 0 , N , K - arr [ idx ] , dp ) ; let exclude = recursion ( arr , idx + 1 , N , K , dp ) ; return ( dp [ idx ] [ K ] = getMaximum ( include , exclude ) ) ; } function largestNumber ( arr , N , K ) { let dp = new Array ( N + 1 ) . fill ( 0 ) . map ( ( ) => new Array ( K + 1 ) . fill ( - 1 ) ) ; let ans = recursion ( arr , 0 , N , K , dp ) ; return ans == " " ? " " : ans ; } let arr = [ 3 , 12 , 9 , 5 , 3 , 4 , 6 , 5 , 10 ] ; let K = 14 ; let N = arr . length ; document . write ( largestNumber ( arr , N , K ) ) ;