# Leetcode 321 Solution

https://leetcode.com/problems/create-maximum-number

## Solution

``````class Solution {
public:
vector<int> select(vector<int>& nums, int k)
{
vector<int> res;
for (int i = 0; i < nums.size(); i++)
{
while(res.size() + nums.size() - i > k && (res.empty() == false && nums[i] > res.back()))
res.pop_back();

if (res.size() < k)
res.push_back(nums[i]);
}
return res;
}

vector<int> maxNumber(vector<int>& nums1, vector<int>& nums2, int k) {
vector<int> res;

for (int k1 = 0; k1 <= k; k1++)
{
int k2 = k - k1;

if (k1 > nums1.size() || k2 > nums2.size())
continue;

auto v1 = select(nums1, k1);
auto v2 = select(nums2, k2);

int i = 0;
int j = 0;

vector<int> v;
while (i < v1.size() || j < v2.size())
{
int selection = 1;
int l = 0;

while (true)
{
if (i + l == v1.size() && j + l == v2.size())
break;
else if (i + l == v1.size())
{
selection = 2;
break;
}
else if (j + l == v2.size())
{
selection = 1;
break;
}
else if (v1[i + l] > v2[j + l])
{
selection = 1;
break;
}
else if (v1[i + l] < v2[j + l])
{
selection = 2;
break;
}

l++;
}

if (selection == 1)
v.push_back(v1[i++]);
else if (selection == 2)
v.push_back(v2[j++]);
}

if (res < v)
res = v;
}

return res;
}
};
``````