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]
To generate a int[] with length k, there are k possibilities.
take 0 digit from nums1[] and k digits from nums2[]
take 1 digit from nums1[] and k - 1 digits from nums2[]
...
...
take k digit from nums1[] and 0 digits from nums2[]
We generate all the result r[0] to r[k] and pick the largest one.
How to generate the r[i], suppose taking i digits from nums1[] and k - i digits from nums2[]?
First we want the max sub-sequence of length i from nums1[]
and the max sub-sequence of length k - i from nums2[]
How to get the max sub-sequence? using mono-stack.
After we have the sub-sequence how to merge them,
if it trivial we put the larger one first, but what if they are same.
32101 <
32102
we need to compare util some digits are different and return the result,
What if one is others prefix?
3210 <
3210XXXX,
we want to use the 3 from 3210XXX first because the XXX could be either a larger number or a smaller number, if it is smaller, we do not care whether we use 3210 first or 3210XXX first, but if it is larger, we must finish use the 3210 in 3210XXX first then we can use XXX, so pick the longer one is always right.
Code:
public class Solution {
public int[] maxNumber(int[] nums1, int[] nums2, int k) {
int[] ret = new int[k];
for(int i = 0; i <= k; i++){
if(nums1.length >= i && nums2.length >= k - i){
int[] r1 = getKMax(nums1,i);
int[] r2 = getKMax(nums2,k-i);
int[] r = merge(r1,r2);
if(compareIntArray(r,0,ret,0) > 0){
ret = r;
}
}
}
return ret;
}
int[] merge(int[] nums1, int[] nums2){
int[] ret = new int[nums1.length + nums2.length];
int i = 0, j = 0, k = 0;
while(k < ret.length){
int cmp = compareIntArray(nums1,i,nums2,j);
if(cmp > 0){
ret[k] = nums1[i++];
} else {
ret[k] = nums2[j++];
}
k++;
}
return ret;
}
int compareIntArray(int[] nums1, int i1, int[] nums2, int i2){
while(i1 < nums1.length && i2 < nums2.length){
if(nums1[i1] < nums2[i2]){
return -1;
} else if(nums1[i1] > nums2[i2]){
return 1;
} else {
i1++;
i2++;
}
}
return (nums1.length - i1) - (nums2.length - i2);
}
public int[] getKMax(int[] nums, int k){
int[] ret = new int[k];
int count = 0;
int i = 0;
while(i < nums.length){
if(count == 0 || nums[i] <= ret[count - 1]){
if(count < k){
ret[count] = nums[i];
count++;
}
} else{
int countLeft = nums.length - i;
while(count > 0 && nums[i] > ret[count - 1] && count + countLeft > k){
ret[count - 1] = 0;
count--;
}
ret[count] = nums[i];
count++;
}
i++;
}
return ret;
}
}