class Solution {
public:
vector<int>choose(vector<int>& nums, int k){
int sz = nums.size();
vector<int> ans;
if(k == 0) return ans;
if(k > nums.size()) return nums;
ans = vector<int>(k, 0);
int top = 0;
for(int i = 0; i < sz; ++i){
while(top && sz - i + top > k && nums[i] > ans[top - 1]) top--;
if(top < k) ans[top++] = nums[i];
}
return ans;
}
vector<int> getk(vector<int>& nums1, vector<int>& nums2, int k){
int l = 0, r = 0;
vector<int> ans;
int sz1 = nums1.size();
int sz2 = nums2.size();
while((l < sz1 || r < sz2) && ans.size() < k){
int tl = l, tr = r;
while(tl < sz1 && tr < sz2 && nums1[tl] == nums2[tr]){
tl++;tr++;
}
if(tl == sz1) ans.push_back(nums2[r++]);
else if(tr == sz2) ans.push_back(nums1[l++]);
else if(nums1[tl] < nums2[tr]) ans.push_back(nums2[r++]);
else ans.push_back(nums1[l++]);
}
return ans;
}
vector<int> maxNumber(vector<int>& nums1, vector<int>& nums2, int k) {
vector<int>res(k, 0);
vector<int>ans(k, 0);
int sz1 = nums1.size();
int sz2 = nums2.size();
for(int i = max(0, k - sz2); i <= min(k, sz1); ++i){
vector<int>v1 = choose(nums1, i);
vector<int>v2 = choose(nums2, k - i);
res = getk(v1, v2, k);
if(res.size() != k) continue;
int sz = res.size();
for(int j = 0; j < sz; ++j){
if(res[j] < ans[j]) break;
if(res[j] > ans[j]){
ans = res;
break;
}
}
}
return ans;
}
};