Given two arrays of length m
and n
with digits 0-9
representing two numbers. Create the maximum number of length k <= m + n
from digits of the two. The relative order of the digits from the same array must be preserved. Return an array of the k
digits. You should try to optimize your time and space complexity.
Example 1:
nums1 = [3, 4, 6, 5]
nums2 = [9, 1, 2, 5, 8, 3]
k = 5
return [9, 8, 6, 5, 3]
Example 2:
nums1 = [6, 7]
nums2 = [6, 0, 4]
k = 5
return [6, 7, 6, 0, 4]
Example 3:
nums1 = [3, 9]
nums2 = [8, 9]
k = 3
return [9, 8, 9]
思想:从nums1中选择i个数,从nums2中选择k-i个数,使得合成的数最大。
分成两个子问题:
1. 如何从一个数组中选择i个数,使这i个数表示的数值是所有候选中最大的。
比如[9, 1, 2, 5, 8, 3] i = 2;如何得到 [9,8]。
2. 如何合并两个数组使得形成最大的值
比如[9, 8, 3] [6,5] ;如何得到[9,8,6,5,3]
Solution
To solve this problem, first let’s look at simpler version:
Easy Version No. 1
Given one array of length n
, create the maximum number of length k
.
The solution to this problem is Greedy with the help of stack. The recipe is as following
- Initialize a empty stack
- Loop through the array
nums
- pop the top of stack if it is smaller than
nums[i]
until- stack is empty
- the digits left is not enough to fill the stack to size
k
- if stack size <
k
pushnums[i]
- pop the top of stack if it is smaller than
- Return stack
Since the stack length is known to be k
, it is very easy to use an array to simulate the stack.
The time complexity is O(n)
since each element is at most been pushed and popped once.
Java