Create Largest Number of Kth Length

Hard
0/120
1 upvote
Asked in company
Amazon

Problem statement

You are given two integer arrays, 'nums1' of length 'm' and 'nums2' of length 'n', which represent the digits of two numbers. You are also given an integer 'k'.

Your task is to create the lexicographically largest possible number of length 'k' by picking digits from the two given arrays. The relative order of digits taken from the same array must be preserved.

Return an array of 'k' digits that represents the answer.


Detailed explanation ( Input/output format, Notes, Images )
Input Format:
The first line contains three space-separated integers: 'm' (length of nums1), 'n' (length of nums2), and 'k'.

The second line contains 'm' space-separated integers, representing the elements of array 'nums1'.

The third line contains 'n' space-separated integers, representing the elements of array 'nums2'.


Output Format:
Print 'k' space-separated integers representing the digits of the maximum number.


Note:
Lexicographically larger means that at the first position where two numbers differ, the number with the larger digit is considered greater. For example, [9, 8, 5] is lexicographically larger than [9, 7, 6].

The relative order of digits from the same source array must be maintained. For example, if you take 4 and 5 from [3, 4, 6, 5], they must appear in the order 4, 5 in the result.
Sample Input 1:
4 6 5
3 4 6 5
9 1 2 5 8 3


Sample Output 1:
9 8 6 5 3


Explanation for Sample 1:
To create the maximum number of length 5, we can try all combinations of taking `i` digits from `nums1` and `5-i` digits from `nums2`.

The optimal choice is to take 2 digits from `nums1` (the best subsequence is `[6, 5]`) and 3 digits from `nums2` (the best subsequence is `[9, 8, 3]`).

Merging these two subsequences `[6, 5]` and `[9, 8, 3]` to get the lexicographically largest result yields `[9, 8, 6, 5, 3]`.


Sample Input 2:
2 3 5
6 7
6 0 4


Sample Output 2:
6 7 6 0 4


Explanation for Sample 2:
Here, k = m + n, so we must use all digits from both arrays. The task simplifies to merging `[6, 7]` and `[6, 0, 4]` while preserving their internal order to create the largest number.


Expected Time Complexity:
The expected time complexity is O(k * (m + n)).


Constraints:
m == nums1.length
n == nums2.length
1 <= m, n <= 500
0 <= nums1[i], nums2[i] <= 9
1 <= k <= m + n

Time limit: 1sec
Approaches (1)
Create Largest Number of Kth Length
Time Complexity

The expected time complexity is O(k * (m + n)).

Space Complexity
Code Solution
(100% EXP penalty)
Create Largest Number of Kth Length
Full screen
Console