Create Maximum Number - Problem
You are given two integer arrays nums1 and nums2 of lengths m and n respectively. nums1 and nums2 represent the digits of two numbers.
You are also given an integer k. Create the maximum number of length k <= m + n from digits of the two numbers. The relative order of the digits from the same array must be preserved.
Return an array of the k digits representing the answer.
Input & Output
Example 1 — Basic Case
$
Input:
nums1 = [3,4,6,5], nums2 = [9,1,2,5,8], k = 5
›
Output:
[9,8,6,5,3]
💡 Note:
Taking all elements and arranging optimally: start with 9 (largest), then 8, then 6 from nums1, then 5 (can be from either), then 3. The merged result maintains relative order from each array.
Example 2 — Limited Selection
$
Input:
nums1 = [6,7], nums2 = [6,0,4], k = 3
›
Output:
[6,7,6]
💡 Note:
We need exactly 3 elements. Best strategy is to take [6,7] from nums1 and [6] from nums2. When merging, we compare [6,7] vs [6,0,4] → [6,7] is larger, so pick 6 from nums1, then 7, then 6 from nums2.
Example 3 — Small k
$
Input:
nums1 = [3,9], nums2 = [8,9], k = 3
›
Output:
[9,8,9]
💡 Note:
Take 2 from nums1 ([3,9]) and 1 from nums2 ([8] - we pick the best subsequence). Merge: compare [3,9] vs [8] → [8] > [3,9], so pick 8. Then compare [3,9] vs [] → pick 3,9. But wait, we need optimal subsequences first: [9] from nums1, [8,9] from nums2 → merge gives [9,8,9].
Constraints
- 1 ≤ nums1.length, nums2.length ≤ 1000
- 1 ≤ nums1.length + nums2.length ≤ 2000
- 0 ≤ nums1[i], nums2[i] ≤ 9
- 1 ≤ k ≤ nums1.length + nums2.length
Visualization
Tap to expand
Understanding the Visualization
1
Input Arrays
Two arrays of digits with specific lengths
2
Select & Merge
Pick k digits total while maintaining relative order within each array
3
Maximum Result
Lexicographically largest possible number
Key Takeaway
🎯 Key Insight: Break into subproblems - find optimal subsequences using monotonic stack, then merge greedily by comparing remaining elements
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code