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 k digits total (where k โ‰ค 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.

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(k * (m + n + k))

We try k+1 possible splits, and for each split we spend O(m+n) time to find max subsequences and O(k) time to merge them

n
2n
โœ“ Linear Growth
Space Complexity
O(k)

We only need space for the result array and temporary arrays during processing

n
2n
โœ“ Linear Space

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.
Asked in
25.0K Views
Medium Frequency
~15 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen