Skip to content
Related Articles

Related Articles

Improve Article

Maximum K-digit number possible from subsequences of two given arrays

  • Difficulty Level : Hard
  • Last Updated : 16 Nov, 2020

Given two arrays arr1[] and arr2[] of length M and N consisting of digits [0, 9] representing two numbers and an integer K(K ≤ M + N), the task is to find the maximum K-digit number possible by selecting subsequences from the given arrays such that the relative order of the digits is the same as in the given array.


Input: arr1[] = {3, 4, 6, 5}, arr2[] = {9, 1, 2, 5, 8, 3}, K = 5
Output: 98653
Explanation: The maximum number that can be formed out of the given arrays arr1[] and arr2[] of length K is 98653.

Input: arr1[] = {6, 7}, arr2[] = {6, 0, 4}, K = 5
Output: 67604
Explanation: The maximum number that can be formed out of the given arrays arr1[] and arr2[] of length K is 67604.

Naive Approach: The idea is to generate all subsequences of length s1 from arr1[] and all subsequences of length (K – s1) from the array arr2[] over all values of s1 in the range [0, K] and keep track of the maximum number so formed by merging both arrays in every iteration.

Time Complexity: O(2N)
Auxiliary Space: O(1)

Efficient Approach: To optimize the above approach, the idea is to get the maximum number from the array arr1[] and of length s1 and maximum number from the array arr2[] and of length (K – s1). Then, merge the two arrays to get the maximum number of length K. Follow the steps below to solve the given problem:

  1. Iterate over the range [0, K] using the variable i and generate all possible decreasing subsequences of length i preserving the same order as in the array arr1[] and subsequences of length (K – i) following the same order as in the array arr2[].
  2. For generating decreasing subsequence of length L of any array arr[] in the above step do the following:
    • Initialize an array ans[] to store the subsequences of length L preserving the same order as in arr[] and Traverse the array arr[] and do the following:
      • Till the last element is less than the current element, then remove the last element from array ans[].
      • If the length of ans[] is less than L then insert the current element in the ans[].
    • After the above steps, the array ans[] in the resultant subsequence.
  3. While generating the subsequences of all possible length in Step 1 using the approach discussed in Step 2 generate the maximum number by merging the two subsequences formed.
  4. After the above steps, print that subsequence which gives maximum number after merging.

Below is the implementation of the above approach:


# Python program for the above approach
# Function to find maximum K-digit number
# possible from subsequences of the
# two arrays nums1[] and nums2[]
def maxNumber(nums1, nums2, k):
    # Store lengths of the arrays
    l1, l2 = len(nums1), len(nums2)
    # Store the resultant subsequence
    rs = []
    # Function to calculate maximum 
    # number from nums of length c_len
    def helper(nums, c_len):
        # Store the resultant maximum
        ans = []  
        # Length of the nums array
        ln = len(nums)
        # Traverse the nums array
        for idx, val in enumerate(nums):
            while ans and ans[-1] < val and ln-idx > c_len-len(ans):
                # If true, then pop
                # out the last element
            # Check the length with
            # required length
            if len(ans) < c_len: 
                # Append the value to ans
        # Return the ans
        return ans  
    # Traverse and pick the maximum
    for s1 in range(max(0, k-l2), min(k, l1)+1):
        # p1 and p2 stores maximum number possible
        # of length s1 and k - s1 from
        # the arrays nums1[] & nums2[]
        p1, p2 = helper(nums1, s1), helper(nums2, k-s1)
        # Update the maximum number
        rs = max(rs, [max(p1, p2).pop(0) for _ in range(k)])
    # Return the result
    return rs  
# Driver Code
arr1 = [3, 4, 6, 5]
arr2 = [9, 1, 2, 5, 8, 3]
K = 5
# Function Call
print(maxNumber(arr1, arr2, K))
[9, 8, 6, 5, 3]

Time Complexity: O(K*(M + N))
Auxiliary Space: O(K)

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 :