Given an array of integers arr[], the task is to maximize the product of the digit sum of every consecutive pairs in a subsequence of length K.

Note: K is always even because pairs will be formed on the even length.

Examples:

Input:_ arr[] = {2, 100, 99, 3, 16}, K = 4_

Output:_ 128_

The optimal subsequence of length 4 is **[2, 100, 99, 16]**

Sum of digits = 2, 2, 18 and 7 respectively.

So Product of digit sums in pairs = 2 * 1 + 18 * 7 = 2 + 126 = 128, which is maximum.

Input:_ arr[] = {10, 5, 9, 101, 24, 2, 20, 14}, K = 6_

Output:_ 69_

The optimal subsequence of length 6 = **[10, 5, 9, 24, 2, 14]**

Sum of digits = 1, 5, 9, 6, 2 and 5 respectively.

So Product of digit sums in pairs = 1 * 5 + 9 * 6 + 2 * 5 = 5 + 54 + 10 = 69, which is maximum.

Recommended: Please try your approach on {IDE} first, before moving on to the solution.

Approach: The idea is to use Dynamic Programming. As we need to find pairs in the array by including or excluding some of the elements from the array to form a subsequence. So let DP[i][j][k] be our dp array which stores the maximum product of the sum of digits of the elements upto index** i** having length** j **and last element as K.

Observations:

  • Odd Length: While choosing the even length subsequence, when current length of the choosen subsequence is odd, then the pair for the last element is to be chosen. Therefore, we have to compute the product of sum of the last and current element and we recur by keeping last as 0 in next call for even length.
  • dp[i][j][k] = max(dp[i][j][k], productDigitSum(arr[k], arr[i]) + solve(i+1, j+1, 0))
  • Even Length: While choosing the odd length subsequence, when current length of the choosen subsequence is even, then we have to just select the first element of the pair. Therefore, we just select the current element as last element for the next recursive call and search for second element for this pair in next recursive call.
  • dp[i][j][k] = max(dp[i][j][k], solve(i+1, j+1, i))
  • Exclude Element: Another option for the current element is to exclude the current element and choose the elements further.
  • dp[i][j][k] = max(dp[i][j][k], solve(i+1, j, k))

#arrays #dynamic programming #mathematical #recursion #number-digits #subsequence

Maximize product of digit sum of consecutive pairs in a subsequence of length K
1.50 GEEK