- 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
- 46 lines of Java from the credited upstream file 321.java.
- The implementation visibly relies on sequence storage.
- 5 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 int[] maxNumber(int[] nums1, int[] nums2, int k) {3 int[] ans = new int[k];4 5 for (int k1 = 0; k1 <= k; ++k1) {6 final int k2 = k - k1;7 if (k1 > nums1.length || k2 > nums2.length)8 continue;9 int[] candidate = merge(maxArray(nums1, k1), maxArray(nums2, k2));10 if (greater(candidate, 0, ans, 0))11 ans = candidate;12 }13 return ans;14 }15 16 private int[] maxArray(int[] nums, int k) {17 List<Integer> res = new ArrayList<>();18 int toPop = nums.length - k;19 for (final int num : nums) {20 while (!res.isEmpty() && res.get(res.size() - 1) < num && toPop > 0) {21 res.remove(res.size() - 1);22 --toPop;23 }24 res.add(num);25 }26 return res.subList(0, k).stream().mapToInt(Integer::intValue).toArray();27 }28 29 30 private int[] merge(int[] nums1, int[] nums2) {31 int[] res = new int[nums1.length + nums2.length];32 for (int i = 0, j = 0, k = 0; k < res.length; ++k)33 res[k] = greater(nums1, i, nums2, j) ? nums1[i++] : nums2[j++];34 return res;35 }36 37 38 private boolean greater(int[] nums1, int i, int[] nums2, int j) {39 while (i < nums1.length && j < nums2.length && nums1[i] == nums2[j]) {40 ++i;41 ++j;42 }43 return j == nums2.length || (i < nums1.length && nums1[i] > nums2[j]);44 }45}46