Skip to content
Related Articles

Related Articles

Improve Article

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

  • Difficulty Level : Hard
  • Last Updated : 25 May, 2021

Given an array of integers arr[], the task is to maximize the product of the digit sum of every consecutive pair in a subsequence of length K.
Note: K is always even because pairs will be formed at an 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] 
The sum of digits = 2, 2, 18 and 7 respectively. 
So the product of digit sums in pairs = 2 * 1 + 18 * 7 = 2 + 126 = 128, which is the 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] 
The sum of digits = 1, 5, 9, 6, 2 and 5 respectively. 
So the product of digit sums in pairs = 1 * 5 + 9 * 6 + 2 * 5 = 5 + 54 + 10 = 69, which is the maximum. 

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 up to index i having length j and, last element K.



Observations:  

  • Odd Length: While choosing the even length subsequence, when the current length of the chosen 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 elements and we recur by keeping last as 0 in the 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 the current length of the chosen subsequence is even, then we have to just select the first element of the pair. Therefore, we just select the current element as the last element for the next recursive call and search for the second element for this pair in the 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))

Below is the implementation of the above approach:  

C++




// C++ implementation to find the
// maximum product of the digit
// sum of the consecutive pairs of
// the subsequence of the length K
 
#include <bits/stdc++.h>
using namespace std;
 
const int MAX = 100;
int dp[1000][MAX][MAX];
 
// Function to find the product
// of two numbers digit sum
// in the pair
int productDigitSum(int x, int y)
{
    int sumx = 0;
 
    // Loop to find the digits of
    // the number
    while (x) {
        sumx += (x % 10);
        x /= 10;
    }
    int sumy = 0;
 
    // Loop to find the digits
    // of other number
    while (y) {
        sumy += (y % 10);
        y /= 10;
    }
    return (sumx * sumy);
}
 
// Function to find the subsequence
// of the length K
int solve(int arr[], int i, int len,
          int prev, int n, int k)
{
    // Base Case
    if (len == k)
        return 0;
 
    // Condition when we didn't reach
    // the length K, but ran out of
    // elements of the array
    if (i == n)
        return INT_MIN;
 
    // Condition if already calculated
    if (dp[i][len][prev])
        return dp[i][len][prev];
 
    int inc = 0, exc = 0;
 
    // If length upto this point is odd
    if (len & 1) {
 
        // 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
        inc = productDigitSum(arr[prev],
                              arr[i])
              + solve(arr, i + 1,
                      len + 1, 0, n, k);
    }
 
    // If length upto this point is even
    else {
        inc = solve(arr, i + 1, len + 1, i, n, k);
    }
 
    // Exclude this current element
    // and recur for next elements.
    exc = solve(arr, i + 1, len, prev, n, k);
 
    // return by memoizing it, by selecting
    // the maximum among two choices.
    return dp[i][len][prev] = max(inc, exc);
}
 
// Driver Code
int main()
{
    int arr[] = { 10, 5, 9, 101, 24, 2, 20, 14 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int k = 6;
    cout << solve(arr, 0, 0, 0, n, k);
}

Java




// Java implementation to find the
// maximum product of the digit
// sum of the consecutive pairs of
// the subsequence of the length K
import java.util.*;
 
class GFG{
     
static int MAX = 100;
static int dp[][][] = new int[1000][MAX][MAX];
 
// Function to find the product
// of two numbers digit sum
// in the pair
static int productDigitSum(int x, int y)
{
    int sumx = 0;
 
    // Loop to find the digits
    // of the number
    while (x > 0)
    {
        sumx += (x % 10);
        x /= 10;
    }
    int sumy = 0;
 
    // Loop to find the digits
    // of other number
    while (y > 0)
    {
        sumy += (y % 10);
        y /= 10;
    }
    return (sumx * sumy);
}
 
// Function to find the subsequence
// of the length K
static int solve(int arr[], int i, int len,
                  int prev, int n, int k)
{
     
    // Base Case
    if (len == k)
        return 0;
 
    // Condition when we didn't reach
    // the length K, but ran out of
    // elements of the array
    if (i == n)
        return Integer.MIN_VALUE;
 
    // Condition if already calculated
    if (dp[i][len][prev] != 0)
        return dp[i][len][prev];
 
    int inc = 0, exc = 0;
 
    // If length upto this point is odd
    if ((len & 1) != 0)
    {
 
        // 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
        inc = (productDigitSum(arr[prev], arr[i]) +
               solve(arr, i + 1, len + 1, 0, n, k));
    }
 
    // If length upto this point is even
    else
    {
        inc = solve(arr, i + 1, len + 1, i, n, k);
    }
 
    // Exclude this current element
    // and recur for next elements.
    exc = solve(arr, i + 1, len, prev, n, k);
 
    // Return by memoizing it, by selecting
    // the maximum among two choices.
    return dp[i][len][prev] = Math.max(inc, exc);
}
 
// Driver Code
public static void main(String []args)
{
    int arr[] = { 10, 5, 9, 101, 24, 2, 20, 14 };
    int n = arr.length;
    int k = 6;
     
    System.out.print(solve(arr, 0, 0, 0, n, k));
}
}
 
// This code is contributed by chitranayal

Python3




# Python3 implementation to find the
# maximum product of the digit
# sum of the consecutive pairs of
# the subsequence of the length K
import sys
 
MAX = 100
dp = []
 
for i in range(1000):
    temp1 = []
    for j in range(MAX):
        temp2 = []
         
        for k in range(MAX):
            temp2.append(0)
        temp1.append(temp2)
         
    dp.append(temp1)
 
# Function to find the product
# of two numbers digit sum
# in the pair
def productDigitSum(x, y):
    sumx = 0
     
    # Loop to find the digits of
    # the number
    while x:
        sumx += x % 10
        x = x // 10
         
    sumy = 0
     
    # Loop to find the digits
    # of other number
    while y:
        sumy += y % 10
        y = y // 10
     
    return sumx * sumy
 
# Function to find the subsequence
# of the length K
def solve(arr, i, len, prev, n, k):
     
    # Base case
    if len == k:
        return 0
     
    # Condition when we didn't reach
    # the length K, but ran out of
    # elements of the array
    if i == n:
        return -sys.maxsize - 1
     
    # Condition if already calculated
    if dp[i][len][prev]:
        return dp[i][len][prev]
     
    # If length upto this point is odd
    if len & 1:
         
        # 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
        inc = (productDigitSum(arr[prev], arr[i]) +
               solve(arr, i + 1, len + 1, i, n, k))
    else:
         
        # If length upto this point is even
        inc = solve(arr, i + 1, len + 1, i, n, k)
     
    # Exclude this current element
    # and recur for next elements.
    exc = solve(arr, i + 1, len, prev, n, k)
     
    # Return by memoizing it, by selecting
    # the maximum among two choices.
    dp[i][len][prev] = max(inc, exc)
    return dp[i][len][prev]
 
# Driver code
arr = [ 10, 5, 9, 101, 24, 2, 20, 14 ]
n = len(arr)
k = 6
print(solve(arr, 0, 0, 0, n, k))
 
# This code is contributed by Shivam Singh

C#




// C# implementation to find the
// maximum product of the digit
// sum of the consecutive pairs of
// the subsequence of the length K
using System;
class GFG{
     
static int MAX = 100;
static int [, ,]dp = new int[1000, MAX, MAX];
 
// Function to find the product
// of two numbers digit sum
// in the pair
static int productDigitSum(int x, int y)
{
    int sumx = 0;
 
    // Loop to find the digits
    // of the number
    while (x > 0)
    {
        sumx += (x % 10);
        x /= 10;
    }
    int sumy = 0;
 
    // Loop to find the digits
    // of other number
    while (y > 0)
    {
        sumy += (y % 10);
        y /= 10;
    }
    return (sumx * sumy);
}
 
// Function to find the subsequence
// of the length K
static int solve(int []arr, int i, int len,
                 int prev, int n, int k)
{
     
    // Base Case
    if (len == k)
        return 0;
 
    // Condition when we didn't reach
    // the length K, but ran out of
    // elements of the array
    if (i == n)
        return Int32.MinValue;
 
    // Condition if already calculated
    if (dp[i, len, prev] != 0)
        return dp[i, len, prev];
 
    int inc = 0, exc = 0;
 
    // If length upto this point is odd
    if ((len & 1) != 0)
    {
 
        // 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
        inc = (productDigitSum(arr[prev], arr[i]) +
               solve(arr, i + 1, len + 1, 0, n, k));
    }
 
    // If length upto this point is even
    else
    {
        inc = solve(arr, i + 1, len + 1, i, n, k);
    }
 
    // Exclude this current element
    // and recur for next elements.
    exc = solve(arr, i + 1, len, prev, n, k);
 
    // Return by memoizing it, by selecting
    // the maximum among two choices.
    return dp[i, len, prev] = Math.Max(inc, exc);
}
 
// Driver Code
public static void Main()
{
    int []arr = { 10, 5, 9, 101, 24, 2, 20, 14 };
    int n = arr.Length;
    int k = 6;
     
    Console.Write(solve(arr, 0, 0, 0, n, k));
}
}
 
// This code is contributed by Nidhi_biet

Javascript




<script>
// Javascript implementation to find the
// maximum product of the digit
// sum of the consecutive pairs of
// the subsequence of the length K
 
 
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 to find the product
// of two numbers digit sum
// in the pair
function productDigitSum(x, y) {
    let sumx = 0;
 
    // Loop to find the digits of
    // the number
    while (x) {
        sumx += (x % 10);
        x = Math.floor(x / 10);
    }
    let sumy = 0;
 
    // Loop to find the digits
    // of other number
    while (y) {
        sumy += (y % 10);
        y = Math.floor(y / 10);
    }
    return (sumx * sumy);
}
 
// Function to find the subsequence
// of the length K
function solve(arr, i, len, prev, n, k) {
    // Base Case
    if (len == k)
        return 0;
 
    // Condition when we didn't reach
    // the length K, but ran out of
    // elements of the array
    if (i == n)
        return Number.MIN_SAFE_INTEGER;
 
    // Condition if already calculated
    if (dp[i][len][prev])
        return dp[i][len][prev];
 
    let inc = 0, exc = 0;
 
    // If length upto this point is odd
    if (len & 1) {
 
        // 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
        inc = productDigitSum(arr[prev],
            arr[i])
            + solve(arr, i + 1,
                len + 1, 0, n, k);
    }
 
    // If length upto this point is even
    else {
        inc = solve(arr, i + 1, len + 1, i, n, k);
    }
 
    // Exclude this current element
    // and recur for next elements.
    exc = solve(arr, i + 1, len, prev, n, k);
 
    // return by memoizing it, by selecting
    // the maximum among two choices.
    return dp[i][len][prev] = Math.max(inc, exc);
}
 
// Driver Code
 
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));
 
 
// This code is contributed by _saurabh_jaiswal
</script>
Output: 
69

 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.




My Personal Notes arrow_drop_up
Recommended Articles
Page :