Create Maximum Number - Problem
You are tasked with creating the maximum possible number by cleverly combining digits from two separate integer arrays. Given two arrays nums1 and nums2 of lengths m and n respectively, where each element represents a single digit (0-9), you need to select exactly k digits to form the largest possible number.
Key Rules:
- You must select exactly
kdigits total (wherek โค m + n) - The relative order of digits from the same array must be preserved
- You can choose any number of digits from each array (including zero from either)
- Return the result as an array representing the maximum number
Example: If nums1 = [3,4,6,5], nums2 = [9,1,2,5,8,3], and k = 5, the answer would be [9,8,6,5,3] - we take the subsequence [6,5] from nums1 and [9,8,3] from nums2, then merge them optimally.
Input & Output
example_1.py โ Basic Case
$
Input:
nums1 = [3,4,6,5], nums2 = [9,1,2,5,8,3], k = 5
โบ
Output:
[9,8,6,5,3]
๐ก Note:
We can take [6,5] from nums1 and [9,8,3] from nums2. Merging them optimally gives [9,8,6,5,3] which is the maximum possible number.
example_2.py โ Take All From One
$
Input:
nums1 = [6,7], nums2 = [6,0,4], k = 5
โบ
Output:
[6,7,6,0,4]
๐ก Note:
We need all 5 digits, so we take all from both arrays. The optimal merge is [6,7,6,0,4] by comparing sequences lexicographically.
example_3.py โ Edge Case k=1
$
Input:
nums1 = [1], nums2 = [1,1,1], k = 1
โบ
Output:
[1]
๐ก Note:
When k=1, we just need to find the maximum digit across both arrays, which is 1.
Constraints
- m == nums1.length
- n == nums2.length
- 1 โค m, n โค 500
- 0 โค nums1[i], nums2[i] โค 9
- 1 โค k โค m + n
- Follow up: Try to optimize your time and space complexity.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code