Approaches

💡

Intuition

Time O(n²)Space O(1)

The brute force approach involves generating all possible combinations of digits from both arrays that can form a number of length k. This is simple but inefficient as it checks every possible combination.

⚙️

Algorithm

3 steps
  1. 1Step 1: Generate all possible combinations of digits from nums1 and nums2 that can form a number of length k.
  2. 2Step 2: For each combination, check if it maintains the relative order of digits from nums1 and nums2.
  3. 3Step 3: Compare all valid combinations and keep track of the maximum number found.
solution.py14 lines
1# Full working Python code
2from itertools import combinations
3
4def maxNumber(nums1, nums2, k):
5    max_num = []
6    for i in range(max(0, k - len(nums2)), min(k, len(nums1)) + 1):
7        comb1 = list(combinations(nums1, i))
8        comb2 = list(combinations(nums2, k - i))
9        for c1 in comb1:
10            for c2 in comb2:
11                merged = list(c1) + list(c2)
12                merged.sort(reverse=True)
13                max_num = max(max_num, merged)
14    return max_num

Complexity note: The time complexity is O(n²) because we generate combinations and compare them, which can be very slow as n increases.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.