leetcode 321 create maximum number

Given two arrays of length m and n with digits 0-9representing 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.

Note: You should try to optimize your time and space complexity.

Example 1:

1
2
3
4
5
6
Input:
nums1 = [3, 4, 6, 5]
nums2 = [9, 1, 2, 5, 8, 3]
k = 5
Output:
[9, 8, 6, 5, 3]

Example 2:

1
2
3
4
5
6
Input:
nums1 = [6, 7]
nums2 = [6, 0, 4]
k = 5
Output:
[6, 7, 6, 0, 4]

Example 3:

1
2
3
4
5
6
Input:
nums1 = [3, 9]
nums2 = [8, 9]
k = 3
Output:
[9, 8, 9]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72


public class {

public int[] maxNumber(int[] nums1, int[] nums2, int k) {
int m = nums1.length;
int n = nums2.length;
int[] result = new int[k];
if (m + n < k) return result;
else if (m+n == k) {
result = merge(nums1, nums2);
return result;
}
else {
for (int i=1; i<=k; i++) {
if (i<nums1.length && k-i < nums2.length) {
int[] l1 = largestK(nums1, i);
int[] l2 = largestK(nums2, k-i);
int[] total = merge(l1, l2);
if (isLarger(total, result))
result = total;
}

}
}
return result;
}
public boolean isLarger(int[] current, int[] old) {
for(int i=0; i<current.length; i++) {
if (current[i] > old[i])
return true;
}
return false;
}

public int[] largestK(int[] nums, int k) {
int t = 0;
int[] ans = new int[k];
for (int i=0; i<nums.length; i++) {
int remain = nums.length - i - 1;
while (remain + (t+1) > k && t > 0 && nums[i] > ans[t-1]) {
t --;
}
if (t < k)
ans[t++] = nums[i];
}
return ans;
}

public int[] merge(int[] nums1, int[] nums2) {
int i=0;
int j=0;
int t=0;
int [] result = new int[nums1.length + nums2.length];
while (i < nums1.length || j < nums2.length) {
if (i >= nums1.length) {
result[t++] = nums2[j++];
}
else if (j >= nums2.length) {
result[t++] = nums1[i++];
}
else if (nums1[i] < nums2[j]) {
result[t++] = nums2[j++];
}
else {
result[t++] = nums1[i++];
}
}
return result;
}

}