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.
Given two arrays nums1 and nums2 of lengths m and n. Now, this is close to the original problem with the difference that we will use all the digits. We create the maximum number of length k = m + n using a greedy approach:
We need k decisions to make, and each time we decide whether ans[i] is from nums1 or nums2.
Compare the subsequent digits when elements are equal; choose the larger number from further elements, if they aren’t equal.
If arrays are the same until their end, then pick either.
For e.g.
1
2
3
4
nums1 =[6,7]nums2 =[6,0,4]k =5ans =[6,7,6,0,4]
We decide to choose the 6 from nums1 at step 1, because 7 > 0. What if they are equal again? We continue to look the next digit until they are not equal. If all digits are equal then choose any one is ok.
This resembles the merge step of the merge sort algorithm but checks further elements when they are equal, leading to a complexity of O(m * n), where m and n are the lengths of nums1 and nums2.
classSolution:
# Get the largest k numbers while keeping relative orderdefmax_number_of_single_array(self, nums: List[int], k: int) -> List[int]:
stack = []
drop = len(nums) - k
for num in nums:
while drop and stack and stack[-1] < num:
stack.pop()
drop -=1 stack.append(num)
return stack[:k]
# Compare two arrays starting from the given indicesdefcompare_two_arrays(self, nums1: List[int], idx1: int, nums2: List[int], idx2: int) -> bool:
while idx1 < len(nums1) and idx2 < len(nums2) and nums1[idx1] == nums2[idx2]:
idx1 +=1 idx2 +=1return idx2 == len(nums2) or (idx1 < len(nums1) and nums1[idx1] > nums2[idx2])
# Merge two arrays to create maximum number of length kdefmerge_two_arrays(self, nums1: List[int], nums2: List[int], k: int) -> List[int]:
ans = []
while k:
if self.compare_two_arrays(nums1, 0, nums2, 0):
ans.append(nums1.pop(0))
else:
ans.append(nums2.pop(0))
k -=1return ans
defmaxNumber(self, nums1: List[int], nums2: List[int], k: int) -> List[int]:
len1, len2 = len(nums1), len(nums2)
result = []
for i in range(max(0, k - len2), min(k, len1) +1):
candidate = self.merge_two_arrays(
self.max_number_of_single_array(nums1, i),
self.max_number_of_single_array(nums2, k - i),
k
)
if candidate > result:
result = candidate
return result