Maximum K-digit number possible from subsequences of two given arrays
Last Updated :
23 Jul, 2025
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.
Examples:
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:
- 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[].
- 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.
- 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.
- After the above steps, print that subsequence which gives maximum number after merging.
Below is the implementation of the above approach:
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
void pop_front(std::vector<int> &v)
{
if (v.size() > 0) {
v.erase(v.begin());
}
}
// Function to calculate maximum
// number from nums of length c_len
vector<int> helper(vector<int> nums, int c_len)
{
// Store the resultant maximum
vector<int> ans;
// Length of the nums array
int ln = nums.size();
// Traverse the nums array
for(int i=0;i<ln;i++)
{
while(ans.size()>0 && ans.back()<nums[i] && ((ln-i) > (c_len-ans.size())))
// If true, then pop
// out the last element
ans.pop_back();
// Check the length with
// required length
if(ans.size()<c_len)
// Append the value to ans
ans.push_back(nums[i]);
}
// Return the ans
return ans;
}
// Function to find maximum K-digit number
// possible from subsequences of the
// two arrays nums1[] and nums2[]
vector<int> maxNumber(vector<int> nums1, vector<int> nums2,int k)
{
// Store lengths of the arrays
int l1 = nums1.size();
int l2 = nums2.size();
// Store the resultant subsequence
vector<int> rs;
// Traverse and pick the maximum
for(int s1=max(0, k-l2);s1<=min(k, l1);s1++)
{
// p1 and p2 stores maximum number possible
// of length s1 and k - s1 from
// the arrays nums1[] & nums2[]
vector<int> p1,p2;
p1 = helper(nums1, s1);
p2 = helper(nums2, k-s1);
// Update the maximum number
vector<int> temp;
for(int j=0;j<k;j++)
{
vector<int> temp2 = max(p1,p2);
int fr = temp2.front();
if(p1>p2)
pop_front(p1);
else
pop_front(p2);
temp.push_back(fr);
}
rs = max(rs, temp);
}
// Return the result
return rs;
}
// Driver Code
int main()
{
vector<int> arr1{3, 4, 6, 5};
vector<int> arr2{9, 1, 2, 5, 8, 3};
int K=5;
// Function Call
vector<int> v = maxNumber(arr1, arr2, K);
for(int i=0;i<v.size();i++)
cout<<v[i]<<" ";
return 0;
}
// This code is contributed by Pushpesh Raj
Java
import java.util.*;
import java.io.*;
// Java program for the above approach
class GFG{
// Function to calculate maximum
// number from nums of length c_len
static ArrayList<Integer> helper(ArrayList<Integer> nums, int c_len)
{
// Store the resultant maximum
ArrayList<Integer> ans = new ArrayList<Integer>();
// Length of the nums array
int ln = nums.size();
// Traverse the nums array
for(int i = 0 ; i < ln ; i++)
{
while(ans.size() > 0 && ans.get(ans.size() - 1) < nums.get(i) && ((ln-i) > (c_len - ans.size()))){
// If true, then pop
// out the last element
ans.remove(ans.size() - 1);
}
// Check the length with
// required length
if(ans.size() < c_len){
// Append the value to ans
ans.add(nums.get(i));
}
}
// Return the ans
return ans;
}
// Returns True if a1 is greater than a2
static boolean comp(ArrayList<Integer> a1, ArrayList<Integer> a2){
int s1 = a1.size();
int s2 = a2.size();
int i1 = 0, i2 = 0;
while(i1 < s1 && i2 < s2){
if(a1.get(i1) > a2.get(i2)){
return true;
}else if(a1.get(i1) < a2.get(i2)){
return false;
}
i1++;
i2++;
}
if(i1 < s1) return true;
return false;
}
// Function to find maximum K-digit number
// possible from subsequences of the
// two arrays nums1[] and nums2[]
static ArrayList<Integer> maxNumber(ArrayList<Integer> nums1, ArrayList<Integer> nums2,int k)
{
// Store lengths of the arrays
int l1 = nums1.size();
int l2 = nums2.size();
// Store the resultant subsequence
ArrayList<Integer> rs = new ArrayList<Integer>();
// Traverse and pick the maximum
for(int s1 = Math.max(0, k-l2) ; s1 <= Math.min(k, l1) ; s1++)
{
// p1 and p2 stores maximum number possible
// of length s1 and k - s1 from
// the arrays nums1[] & nums2[]
ArrayList<Integer> p1 = new ArrayList<Integer>();
ArrayList<Integer> p2 = new ArrayList<Integer>();
p1 = helper(nums1, s1);
p2 = helper(nums2, k-s1);
// Update the maximum number
ArrayList<Integer> temp = new ArrayList<Integer>();
for(int j = 0 ; j < k ; j++)
{
ArrayList<Integer> temp2 = comp(p1, p2) ? p1 : p2;
int fr = temp2.get(0);
if(comp(p1, p2)){
if(p1.size() > 0){
p1.remove(0);
}
}else{
if(p2.size() > 0){
p2.remove(0);
}
}
temp.add(fr);
}
rs = comp(rs, temp) ? rs : temp;
}
// Return the result
return rs;
}
public static void main(String args[])
{
ArrayList<Integer> arr1 = new ArrayList<Integer>(
List.of(
3, 4, 6, 5
)
);
ArrayList<Integer> arr2 = new ArrayList<Integer>(
List.of(
9, 1, 2, 5, 8, 3
)
);
int K = 5;
// Function Call
ArrayList<Integer> v = maxNumber(arr1, arr2, K);
for(int i = 0 ; i < v.size() ; i++){
System.out.print(v.get(i) + " ");
}
}
}
// This code is contributed by subhamgoyal2014.
Python3
# 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
ans.pop(-1)
# Check the length with
# required length
if len(ans) < c_len:
# Append the value to ans
ans.append(val)
# 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))
C#
// C# code for the above approach
using System;
using System.Collections.Generic;
class GFG {
// Function to calculate maximum
// number from nums of length c_len
static List<int> Helper(List<int> nums, int c_len)
{
// Store the resultant maximum
List<int> ans = new List<int>();
// Length of the nums array
int ln = nums.Count;
// Traverse the nums array
for (int i = 0; i < ln; i++) {
while (ans.Count > 0
&& ans[ans.Count - 1] < nums[i]
&& ((ln - i) > (c_len - ans.Count))) {
// If true, then pop out the last element
ans.RemoveAt(ans.Count - 1);
}
// Check the length with required length
if (ans.Count < c_len) {
// Append the value to ans
ans.Add(nums[i]);
}
}
// Return the ans
return ans;
}
// Returns True if a1 is greater than a2
static bool Comp(List<int> a1, List<int> a2)
{
int s1 = a1.Count;
int s2 = a2.Count;
int i1 = 0, i2 = 0;
while (i1 < s1 && i2 < s2) {
if (a1[i1] > a2[i2]) {
return true;
}
else if (a1[i1] < a2[i2]) {
return false;
}
i1++;
i2++;
}
if (i1 < s1)
return true;
return false;
}
// Function to find maximum K-digit number
// possible from subsequences of the
// two arrays nums1[] and nums2[]
static List<int> MaxNumber(List<int> nums1,
List<int> nums2, int k)
{
// Store lengths of the arrays
int l1 = nums1.Count;
int l2 = nums2.Count;
// Store the resultant subsequence
List<int> rs = new List<int>();
// Traverse and pick the maximum
for (int s1 = Math.Max(0, k - l2);
s1 <= Math.Min(k, l1); s1++) {
// p1 and p2 stores maximum number possible
// of length s1 and k - s1 from
// the arrays nums1[] & nums2[]
List<int> p1 = new List<int>();
List<int> p2 = new List<int>();
p1 = Helper(nums1, s1);
p2 = Helper(nums2, k - s1);
// Update the maximum number
List<int> temp = new List<int>();
for (int j = 0; j < k; j++) {
List<int> temp2 = Comp(p1, p2) ? p1 : p2;
int fr = temp2[0];
if (Comp(p1, p2)) {
if (p1.Count > 0) {
p1.RemoveAt(0);
}
}
else {
if (p2.Count > 0) {
p2.RemoveAt(0);
}
}
temp.Add(fr);
}
rs = Comp(rs, temp) ? rs : temp;
}
// Return the result
return rs;
}
public static void Main(string[] args)
{
List<int> arr1 = new List<int>{ 3, 4, 6, 5 };
List<int> arr2 = new List<int>{ 9, 1, 2, 5, 8, 3 };
int k = 5;
List<int> result = MaxNumber(arr1, arr2, k);
foreach(int i in result) { Console.Write(i + " "); }
}
}
// This code is contributed by lokeshpotta20.
JavaScript
<script>
// javascript program for the above approach
class GFG
{
// Function to calculate maximum
// number from nums of length c_len
static helper(nums, c_len)
{
// Store the resultant maximum
var ans = new Array();
// Length of the nums array
var ln = nums.length;
// Traverse the nums array
for (let i=0; i < ln; i++)
{
while (ans.length > 0 && ans[ans.length - 1] < nums[i] && ((ln - i) > (c_len - ans.length)))
{
// If true, then pop
// out the last element
ans.splice(ans.length - 1,1);
}
// Check the length with
// required length
if (ans.length < c_len)
{
// Append the value to ans
(ans.push(nums[i]) > 0);
}
}
// Return the ans
return ans;
}
// Returns True if a1 is greater than a2
static comp(a1, a2)
{
var s1 = a1.length;
var s2 = a2.length;
var i1 = 0;
var i2 = 0;
while (i1 < s1 && i2 < s2)
{
if (a1[i1] > a2[i2])
{
return true;
}
else if (a1[i1] < a2[i2])
{
return false;
}
i1++;
i2++;
}
if (i1 < s1)
{
return true;
}
return false;
}
// Function to find maximum K-digit number
// possible from subsequences of the
// two arrays nums1[] and nums2[]
static maxNumber(nums1, nums2, k)
{
// Store lengths of the arrays
var l1 = nums1.length;
var l2 = nums2.length;
// Store the resultant subsequence
var rs = new Array();
// Traverse and pick the maximum
for (let s1=Math.max(0, k-l2); s1 <= Math.min(k,l1); s1++)
{
// p1 and p2 stores maximum number possible
// of length s1 and k - s1 from
// the arrays nums1[] & nums2[]
var p1 = new Array();
var p2 = new Array();
p1 = GFG.helper(nums1, s1);
p2 = GFG.helper(nums2, k - s1);
// Update the maximum number
var temp = new Array();
for (let j=0; j < k; j++)
{
var temp2 = GFG.comp(p1, p2) ? p1 : p2;
var fr = temp2[0];
if (GFG.comp(p1, p2))
{
if (p1.length > 0)
{
p1.splice(0,1);
}
}
else
{
if (p2.length > 0)
{
p2.splice(0,1);
}
}
(temp.push(fr) > 0);
}
rs = GFG.comp(rs, temp) ? rs : temp;
}
// Return the result
return rs;
}
static main(args)
{
var arr1 = [3,6,4,5];
var arr2 = [9,1,2,5,8,3];
var K = 5;
// Function Call
var v = GFG.maxNumber(arr1, arr2, K);
for (let i=0; i < v.length; i++)
{
document.write(v[i] + " ");
}
}
}
GFG.main([]);
</script>
Time Complexity: O(K*(M + N))
Auxiliary Space: O(K)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem