[LeetCode] Create Maximum Number

321. Create Maximum Number

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.

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
class Solution {
public:
vector<int> maxNumber(vector<int>& A, vector<int>& B, int k) {
int n = A.size(), m = B.size();
if(n > m) return maxNumber(B, A, k);

vector<int> res;
for(int i = max(k - m, 0); i <= min(n, k); i++) {
res = max(res, merge(pick(A, i), pick(B, k - i)));
}
return res;
}
deque<int> pick(vector<int>& A, int pick) {
deque<int> res;
int n = A.size(), remove = n - pick;
for(int i = 0; i < n; i++) {
while(remove and !res.empty() and res.back() < A[i]) {
remove--;
res.pop_back();
}
res.push_back(A[i]);
}
res.resize(pick);

return res;
}

vector<int> merge(deque<int> A, deque<int> B) {
vector<int> res;
while(!A.empty() or !B.empty()) {
deque<int>& best = A > B ? A : B;
res.push_back(best[0]);
best.pop_front();
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/24/PS/LeetCode/create-maximum-number/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.