- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 41 lines of C++ from the credited upstream file 321.cpp.
- The implementation visibly relies on sequence storage.
- 4 loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public:3 vector<int> maxNumber(vector<int>& nums1, vector<int>& nums2, int k) {4 vector<int> ans;5 6 for (int k1 = 0; k1 <= k; ++k1) {7 const int k2 = k - k1;8 if (k1 > nums1.size() || k2 > nums2.size())9 continue;10 ans = max(ans, merge(maxArray(nums1, k1), maxArray(nums2, k2)));11 }12 13 return ans;14 }15 16 private:17 vector<int> maxArray(const vector<int>& nums, int k) {18 vector<int> res;19 int toPop = nums.size() - k;20 for (const int num : nums) {21 while (!res.empty() && res.back() < num && toPop-- > 0)22 res.pop_back();23 res.push_back(num);24 }25 return {res.begin(), res.begin() + k};26 }27 28 29 vector<int> merge(const vector<int>& nums1, const vector<int>& nums2) {30 vector<int> res;31 auto s1 = nums1.cbegin();32 auto s2 = nums2.cbegin();33 while (s1 != nums1.cend() || s2 != nums2.cend())34 if (lexicographical_compare(s1, nums1.cend(), s2, nums2.cend()))35 res.push_back(*s2++);36 else37 res.push_back(*s1++);38 return res;39 }40};41