
Problem
Solution
Submissions
Create Maximum Number
Certification: Advanced Level
Accuracy: 100%
Submissions: 1
Points: 15
Write a Java program to create the maximum number of length k from two given arrays nums1 and nums2. The resulting number should be formed by selecting digits from either or both arrays, maintaining the relative order of digits from the same array. Return the maximum number as an array of digits.
Example 1
- Input: nums1 = [3,4,6,5], nums2 = [9,1,2,5,8,3], k = 5
- Output: [9,8,6,5,3]
- Explanation:
- Step 1: We need to pick k=5 digits in total to form the maximum number.
- Step 2: We can select a certain number of digits from nums1 and the rest from nums2.
- Step 3: For example, we could pick 3 digits from nums1 and 2 digits from nums2.
- Step 4: From nums1, the maximum 3 digits we can pick while maintaining order are [6,5,3] or [4,6,5].
- Step 5: From nums2, the maximum 2 digits we can pick while maintaining order are [9,8].
- Step 6: After merging [4,6,5] and [9,8], and comparing all possible combinations, [9,8,6,5,3] forms the maximum possible number.
Example 2
- Input: nums1 = [6,7], nums2 = [6,0,4], k = 5
- Output: [6,7,6,0,4]
- Explanation:
- Step 1: We need to pick k=5 digits in total to form the maximum number.
- Step 2: Since nums1.length + nums2.length = 5, we must select all digits from both arrays.
- Step 3: We need to merge the two arrays to create the maximum possible number.
- Step 4: When merging, we choose the larger digit when comparing elements.
- Step 5: The merged result is [6,7,6,0,4], which is the maximum possible number we can form.
Constraints
- 1 ≤ nums1.length, nums2.length ≤ 10000
- 0 ≤ nums1[i], nums2[i] ≤ 9
- 1 ≤ k ≤ nums1.length + nums2.length
- Time Complexity: O((n+m)^3), where n and m are the lengths of the input arrays
- Space Complexity: O(k)
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Break down the problem into three sub-problems:
- a. Find the maximum number of length i from nums1
- b. Find the maximum number of length j from nums2, where i + j = k
- c. Merge the two maximum numbers to form the maximum combined number
- For finding the maximum number from a single array, use a monotonic stack approach.
- For merging two arrays, always choose the larger digit. If the digits are equal, look ahead to determine which sequence will yield a larger number.
- Try all possible values of i and j such that i + j = k and i ≤ nums1.length and j ≤ nums2.length.
- Return the maximum result among all combinations.