Skip to content
Problem 321 · LeetCode 321(opens in a new tab)

Create Maximum Number

HardArrays

You get two arrays of digits, nums1 and nums2, each one the digits of a number, and a length k that is at most their combined length.

Build the largest possible number with exactly k digits by choosing digits from both arrays. Digits taken from the same array must keep their original order, but you may interleave the two arrays however you like. Return the k digits as an array.

Example 1

Input:  nums1 = [4, 7], nums2 = [8, 3, 9], k = 3
Output: [9, 4, 7]
Why:    take 9 from nums2 first, then 4 and 7 from nums1
2 more examples and the constraints

Example 2

Input:  nums1 = [5, 0], nums2 = [5, 3, 1], k = 5
Output: [5, 5, 3, 1, 0]
Why:    every digit is used; the 5 of nums2 goes first because 3 beats 0

Example 3

Input:  nums1 = [2, 9], nums2 = [9, 2], k = 2
Output: [9, 9]
Why:    one 9 from each array

Constraints

  • 1 ≤ length of nums1, length of nums2 ≤ 500
  • Every element is a digit from 0 to 9
  • 1 ≤ k ≤ length of nums1 + length of nums2
  • Neither array starts with 0

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Split, scan windows, mergeO(k·(m² + n²))
  2. Monotonic stack pick + mergeO(k·(m+n))

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 500 digits each, k = 500Verdict
Split, scan windows, mergeO(k·(m² + n²))
Right idea, slow picks
Monotonic stack pick + mergeO(k·(m+n))
Best; linear picks

m, n = lengths of nums1 and nums2; k = digits to keep.

Edge cases to test

  • Ties in the merge. [5, 0] and [5, 3, 1] with k = 5 must take the second array's 5 first, because 3 beats 0.
  • k uses every digit. Then each array is kept whole and only the merge matters.
  • One array is not used. With [9, 8, 7] and [1, 1], k = 3, the best split takes all three from nums1.
  • Splits out of range. i must satisfy i ≤ m and k − i ≤ n, so start at max(0, k − n).

Common mistakes

  • Merging by comparing only the two heads, which breaks on equal digits.
  • Trying only one split, such as taking as much as possible from the larger array.
  • Popping from the stack without counting drops, so fewer than t digits remain.

How to talk through it

  1. 1Clarify. Must digits from one array stay in order? Can k use every digit? Are leading zeros allowed in the answer?
  2. 2Split the problem. Fix how many digits come from each array; then it is two picks and a merge.
  3. 3Pick with a stack. Bigger digits should come first, so pop smaller tops while drops remain.
  4. 4Merge carefully. Compare the remaining lists as a whole so ties look ahead.
  5. 5Test out loud. Run a tie in the merge, k = m + n, and a case where one array is skipped.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?