You are tasked with creating the maximum possible number by cleverly combining digits from two separate integer arrays. Given two arrays nums1 and nums2 of lengths m and n respectively, where each element represents a single digit (0-9), you need to select exactly k digits to form the largest possible number.
Key Rules:
You must select exactly k digits total (where k โค m + n)
The relative order of digits from the same array must be preserved
You can choose any number of digits from each array (including zero from either)
Return the result as an array representing the maximum number
Example: If nums1 = [3,4,6,5], nums2 = [9,1,2,5,8,3], and k = 5, the answer would be [9,8,6,5,3] - we take the subsequence [6,5] from nums1 and [9,8,3] from nums2, then merge them optimally.
Input & Output
example_1.py โ Basic Case
$Input:nums1 = [3,4,6,5], nums2 = [9,1,2,5,8,3], k = 5
โบOutput:[9,8,6,5,3]
๐ก Note:We can take [6,5] from nums1 and [9,8,3] from nums2. Merging them optimally gives [9,8,6,5,3] which is the maximum possible number.
example_2.py โ Take All From One
$Input:nums1 = [6,7], nums2 = [6,0,4], k = 5
โบOutput:[6,7,6,0,4]
๐ก Note:We need all 5 digits, so we take all from both arrays. The optimal merge is [6,7,6,0,4] by comparing sequences lexicographically.
example_3.py โ Edge Case k=1
$Input:nums1 = [1], nums2 = [1,1,1], k = 1
โบOutput:[1]
๐ก Note:When k=1, we just need to find the maximum digit across both arrays, which is 1.
Time & Space Complexity
Time Complexity
โฑ๏ธ
O(k * (m + n + k))
We try k+1 possible splits, and for each split we spend O(m+n) time to find max subsequences and O(k) time to merge them
n
2n
โ Linear Growth
Space Complexity
O(k)
We only need space for the result array and temporary arrays during processing
Follow up: Try to optimize your time and space complexity.
Asked in
Create Maximum Number โ Solution
The optimal solution uses a three-step greedy approach: 1) Try all valid ways to split k digits between the arrays, 2) Use monotonic stacks to find the maximum subsequence of required length from each array, and 3) Merge greedily by comparing remaining sequences lexicographically. This achieves O(k ร (m + n + k)) time complexity, much better than the exponential brute force approach.
Common Approaches
Approach
Time
Space
Notes
โ
Greedy with Monotonic Stack (Optimal)
O(k * (m + n + k))
O(k)
Use greedy strategy with monotonic stacks to find optimal solution efficiently
Brute Force (Try All Combinations)
O(2^(m+n) * k)
O(2^(m+n) * k)
Try all possible ways to distribute k digits between the two arrays and merge them
Greedy with Monotonic Stack (Optimal) โ Algorithm Steps
For each possible split i (digits from nums1) and k-i (digits from nums2)
Use monotonic stack to find maximum subsequence of length i from nums1
Use monotonic stack to find maximum subsequence of length k-i from nums2
Merge the two subsequences greedily by comparing remaining sequences
Keep track of the overall maximum result
Visualization
Tap to expand
Step-by-Step Walkthrough
1
Split Strategy
Try all valid ways to distribute k digits between arrays
2
Monotonic Stack
Use monotonic stack to find maximum subsequence from each array
3
Greedy Merge
Merge subsequences by always choosing lexicographically larger sequence
4
Track Maximum
Keep the best result across all splits
Code -
solution.c โ C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int* maxArray(int* nums, int numsSize, int k, int* returnSize) {
if (k >= numsSize) {
int* result = (int*)malloc(numsSize * sizeof(int));
memcpy(result, nums, numsSize * sizeof(int));
*returnSize = numsSize;
return result;
}
if (k == 0) {
*returnSize = 0;
return NULL;
}
int* stack = (int*)malloc(numsSize * sizeof(int));
int top = -1;
int toDrop = numsSize - k;
for (int i = 0; i < numsSize; i++) {
while (top >= 0 && stack[top] < nums[i] && toDrop > 0) {
top--;
toDrop--;
}
stack[++top] = nums[i];
}
while (toDrop > 0) {
top--;
toDrop--;
}
int* result = (int*)malloc((top + 1) * sizeof(int));
memcpy(result, stack, (top + 1) * sizeof(int));
*returnSize = top + 1;
free(stack);
return result;
}
int isGreater(int* nums1, int size1, int* nums2, int size2) {
for (int i = 0; i < size1 && i < size2; i++) {
if (nums1[i] > nums2[i]) return 1;
if (nums1[i] < nums2[i]) return 0;
}
return size1 > size2;
}
int* merge(int* nums1, int size1, int* nums2, int size2, int* returnSize) {
int* result = (int*)malloc((size1 + size2) * sizeof(int));
int i = 0, j = 0, k = 0;
while (i < size1 || j < size2) {
if (i >= size1) {
while (j < size2) result[k++] = nums2[j++];
break;
} else if (j >= size2) {
while (i < size1) result[k++] = nums1[i++];
break;
} else if (isGreater(nums1 + i, size1 - i, nums2 + j, size2 - j)) {
result[k++] = nums1[i++];
} else {
result[k++] = nums2[j++];
}
}
*returnSize = k;
return result;
}
int* maxNumber(int* nums1, int nums1Size, int* nums2, int nums2Size, int k, int* returnSize) {
int* maxResult = (int*)calloc(k, sizeof(int));
*returnSize = k;
for (int i = (k - nums2Size > 0 ? k - nums2Size : 0);
i <= (k < nums1Size ? k : nums1Size); i++) {
int size1, size2, candidateSize;
int* max1 = maxArray(nums1, nums1Size, i, &size1);
int* max2 = maxArray(nums2, nums2Size, k - i, &size2);
int* candidate = merge(max1, max2, size1, size2, &candidateSize);
if (isGreater(candidate, candidateSize, maxResult, k)) {
memcpy(maxResult, candidate, k * sizeof(int));
}
if (max1) free(max1);
if (max2) free(max2);
free(candidate);
}
return maxResult;
}
int main() {
int nums1[] = {3, 4, 6, 5};
int nums2[] = {9, 1, 2, 5, 8, 3};
int k = 5;
int returnSize;
int* result = maxNumber(nums1, 4, nums2, 6, k, &returnSize);
printf("[");
for (int i = 0; i < returnSize; i++) {
printf("%d", result[i]);
if (i < returnSize - 1) printf(",");
}
printf("]\n");
free(result);
return 0;
}
Time & Space Complexity
Time Complexity
โฑ๏ธ
O(k * (m + n + k))
We try k+1 possible splits, and for each split we spend O(m+n) time to find max subsequences and O(k) time to merge them
n
2n
โ Linear Growth
Space Complexity
O(k)
We only need space for the result array and temporary arrays during processing
n
2n
โ Linear Space
Constraints
m == nums1.length
n == nums2.length
1 โค m, n โค 500
0 โค nums1[i], nums2[i] โค 9
1 โค k โค m + n
Follow up: Try to optimize your time and space complexity.
25.0K Views
MediumFrequency
~15 minAvg. Time
850 Likes
Ln 1, Col 1
Smart Actions
๐กExplanation
AI Ready
๐ก SuggestionTabto acceptEscto dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen
Algorithm Visualization
Pinch to zoom โข Tap outside to close
Test Cases
0 passed
0 failed
3 pending
Select Compiler
Choose a programming language
Compiler list would appear here...
AI Editor Features
Header Buttons
๐ก
Explain
Get a detailed explanation of your code. Select specific code or analyze the entire file. Understand algorithms, logic flow, and complexity.
๐ง
Fix
Automatically detect and fix issues in your code. Finds bugs, syntax errors, and common mistakes. Shows you what was fixed.
๐ก
Suggest
Get improvement suggestions for your code. Best practices, performance tips, and code quality recommendations.
๐ฌ
Ask AI
Open an AI chat assistant to ask any coding questions. Have a conversation about your code, get help with debugging, or learn new concepts.
Smart Actions (Slash Commands)
๐ง
/fix Enter
Find and fix issues in your code. Detects common problems and applies automatic fixes.
๐ก
/explain Enter
Get a detailed explanation of what your code does, including time/space complexity analysis.
๐งช
/tests Enter
Automatically generate unit tests for your code. Creates comprehensive test cases.
๐
/docs Enter
Generate documentation for your code. Creates docstrings, JSDoc comments, and type hints.
โก
/optimize Enter
Get performance optimization suggestions. Improve speed and reduce memory usage.
AI Code Completion (Copilot-style)
๐ป
Ghost Text Suggestions
As you type, AI suggests code completions shown in gray text. Works with keywords like def, for, if, etc.
Tabto acceptEscto dismiss
๐ฌ
Comment-to-Code
Write a comment describing what you want, and AI generates the code. Try: # two sum, # binary search, # fibonacci
๐ก
Pro Tip: Select specific code before using Explain, Fix, or Smart Actions to analyze only that portion. Otherwise, the entire file will be analyzed.