[Leetcode] 321.Create Maximum Number
[Description]
[Analysis]
To create max number of length k from two arrays, you need to create max number of length i from array one and max number of length k-i from array two, then combine them together. After trying all possible i, you will get the max number created from two arrays.
[Code]
#include <iostream>
#include <vector>
using namespace std;
class Solution {
private:
vector<vector<int>> helper(vector<int>& nums, int k) {
vector<vector<int>> numsTopK(k + 1, vector<int>{});
vector<int> tmp;
for (int i = 0; i < nums.size(); i++) {
for (int j = k; j > 0; j--) {
if (numsTopK[j].size() < j) {
numsTopK[j].push_back(nums[i]);
} else {
tmp = numsTopK[j - 1];
tmp.push_back(nums[i]);
if (compare(tmp, numsTopK[j])) {
numsTopK[j] = tmp;
}
}
}
}
return numsTopK;
}
vector<int> merge(vector<int>& nums1, vector<int>& nums2) {
vector<int> result;
int i = 0, j = 0;
while (i < nums1.size() && j < nums2.size()) {
if (compare(nums1, nums2, i, j)) {
result.push_back(nums1[i]);
i++;
} else {
result.push_back(nums2[j]);
j++;
}
}
while (i < nums1.size()) {
result.push_back(nums1[i]);
i++;
}
while (j < nums2.size()) {
result.push_back(nums2[j]);
j++;
}
return result;
}
bool compare(vector<int>& nums1, vector<int>& nums2, int i, int j) {
while (i < nums1.size() && j < nums2.size()) {
if (nums1[i] > nums2[j]) {
return true;
} else if (nums1[i] < nums2[j]) {
return false;
} else {
i++;
j++;
}
}
if (i == nums1.size()) {
return false;
}
return true;
}
bool compare(vector<int>& nums1, vector<int>& nums2) {
if (nums1.size() > nums2.size()) {
return true;
} else if (nums1.size() < nums2.size()) {
return false;
} else {
for (int i = 0; i < nums1.size(); i++) {
if (nums1[i] > nums2[i]) {
return true;
} else if (nums1[i] < nums2[i]) {
return false;
}
}
}
return true;
}
public:
vector<int> maxNumber(vector<int>& nums1, vector<int>& nums2, int k) {
vector<vector<int>> nums1TopK = helper(nums1, k);
vector<vector<int>> nums2TopK = helper(nums2, k);
vector<int> maxResult;
vector<int> tmp;
for (int i = 0; i <= k; i++) {
tmp = merge(nums1TopK[i], nums2TopK[k - i]);
if (compare(tmp, maxResult)) {
maxResult = tmp;
}
}
return maxResult;
}
};
int main() {
vector<int> nums1{2,5,6,4,4,0};
vector<int> nums2{7, 3, 8, 0, 6, 5, 7, 6, 2};
Solution so;
so.maxNumber(nums1, nums2, 15);
return 0;
}
[Complexity]
Time Complexity: O(n * k)
Space Complexity: O( k^2 )
The solution is pretty simple so I will try to optimize the solution sooner.