Problem solution · Java

Create Maximum Number

Create Maximum Number: a Java solution using direct simulation. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Direct simulation
Source
walkccc LeetCode Solutions
Length
46 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Direct simulation

For Create Maximum Number, the implementation follows the problem’s operations directly while maintaining only the state needed for the next decision.

  1. Translate each rule into one explicit state update.
  2. Maintain the invariant after every processed item.
  3. 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.

Source

Code and credit

This code comes from walkccc LeetCode Solutions by P.-Y. Chen (walkccc) and is used under the MIT licence.

Full codeCreate Maximum Number · JavaJava
Use this to learn the idea, then write your own version.
class Solution {  public int[] maxNumber(int[] nums1, int[] nums2, int k) {    int[] ans = new int[k];     for (int k1 = 0; k1 <= k; ++k1) {      final int k2 = k - k1;      if (k1 > nums1.length || k2 > nums2.length)        continue;      int[] candidate = merge(maxArray(nums1, k1), maxArray(nums2, k2));      if (greater(candidate, 0, ans, 0))        ans = candidate;    }    return ans;  }   private int[] maxArray(int[] nums, int k) {    List<Integer> res = new ArrayList<>();    int toPop = nums.length - k;    for (final int num : nums) {      while (!res.isEmpty() && res.get(res.size() - 1) < num && toPop > 0) {        res.remove(res.size() - 1);        --toPop;      }      res.add(num);    }    return res.subList(0, k).stream().mapToInt(Integer::intValue).toArray();  }   // Merges nums1 and nums2.  private int[] merge(int[] nums1, int[] nums2) {    int[] res = new int[nums1.length + nums2.length];    for (int i = 0, j = 0, k = 0; k < res.length; ++k)      res[k] = greater(nums1, i, nums2, j) ? nums1[i++] : nums2[j++];    return res;  }   // Returns true if nums1[i..n) > nums2[j..n).  private boolean greater(int[] nums1, int i, int[] nums2, int j) {    while (i < nums1.length && j < nums2.length && nums1[i] == nums2[j]) {      ++i;      ++j;    }    return j == nums2.length || (i < nums1.length && nums1[i] > nums2[j]);  }} 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗