Maximize product of digit sum of consecutive pairs in a subsequence of length K | Javascript implementation to find the maximum product of the digit sum of the consecutive pairs of the subsequence of the length K ; Function to find the product of two numbers digit sum in the pair ; Loop to find the digits of the number ; Loop to find the digits of other number ; Function to find the subsequence of the length K ; Base Case ; Condition when we didn 't reach  the length K, but ran out of  elements of the array ; Condition if already calculated ; If length upto this point is odd ; If length is odd , it means we need second element of this current pair , calculate the product of digit sum of current and previous element and recur by moving towards next index ; If length upto this point is even ; Exclude this current element and recur for next elements . ; return by memoizing it , by selecting the maximum among two choices . ; Driver Code
const MAX = 100 ; let dp = [ ] for ( let i = 0 ; i < 1000 ; i ++ ) { let temp1 = [ ] ; for ( let j = 0 ; j < MAX ; j ++ ) { let temp2 = [ ] ; for ( let k = 0 ; k < MAX ; k ++ ) { temp2 . push ( 0 ) } temp1 . push ( temp2 ) } dp . push ( temp1 ) } function productDigitSum ( x , y ) { let sumx = 0 ; while ( x ) { sumx += ( x % 10 ) ; x = Math . floor ( x / 10 ) ; } let sumy = 0 ; while ( y ) { sumy += ( y % 10 ) ; y = Math . floor ( y / 10 ) ; } return ( sumx * sumy ) ; } function solve ( arr , i , len , prev , n , k ) { if ( len == k ) return 0 ; if ( i == n ) return Number . MIN_SAFE_INTEGER ; if ( dp [ i ] [ len ] [ prev ] ) return dp [ i ] [ len ] [ prev ] ; let inc = 0 , exc = 0 ; if ( len & 1 ) { inc = productDigitSum ( arr [ prev ] , arr [ i ] ) + solve ( arr , i + 1 , len + 1 , 0 , n , k ) ; } else { inc = solve ( arr , i + 1 , len + 1 , i , n , k ) ; } exc = solve ( arr , i + 1 , len , prev , n , k ) ; return dp [ i ] [ len ] [ prev ] = Math . max ( inc , exc ) ; } let arr = [ 10 , 5 , 9 , 101 , 24 , 2 , 20 , 14 ] ; let n = arr . length ; let k = 6 ; document . write ( solve ( arr , 0 , 0 , 0 , n , k ) ) ;