LeetCode 0321. Create Maximum Number Solution in Java, Python, C++, JavaScript, Go & Rust | Explanation + Code

CoderIndeed
0
0321. Create Maximum Number

Description

You are given two integer arrays nums1 and nums2 of lengths m and n respectively. nums1 and nums2 represent the digits of two numbers. You are also given an integer k.

Create the maximum number of length k <= m + n from digits of the two numbers. The relative order of the digits from the same array must be preserved.

Return an array of the k digits representing the answer.

 

Example 1:

Input: nums1 = [3,4,6,5], nums2 = [9,1,2,5,8,3], k = 5
Output: [9,8,6,5,3]

Example 2:

Input: nums1 = [6,7], nums2 = [6,0,4], k = 5
Output: [6,7,6,0,4]

Example 3:

Input: nums1 = [3,9], nums2 = [8,9], k = 3
Output: [9,8,9]

 

Constraints:

  • m == nums1.length
  • n == nums2.length
  • 1 <= m, n <= 500
  • 0 <= nums1[i], nums2[i] <= 9
  • 1 <= k <= m + n
  • nums1 and nums2 do not have leading zeros.

Solutions

Solution 1

PythonJavaC++GoTypeScript
class Solution: def maxNumber(self, nums1: List[int], nums2: List[int], k: int) -> List[int]: def f(nums: List[int], k: int) -> List[int]: n = len(nums) stk = [0] * k top = -1 remain = n - k for x in nums: while top >= 0 and stk[top] < x and remain > 0: top -= 1 remain -= 1 if top + 1 < k: top += 1 stk[top] = x else: remain -= 1 return stk def compare(nums1: List[int], nums2: List[int], i: int, j: int) -> bool: if i >= len(nums1): return False if j >= len(nums2): return True if nums1[i] > nums2[j]: return True if nums1[i] < nums2[j]: return False return compare(nums1, nums2, i + 1, j + 1) def merge(nums1: List[int], nums2: List[int]) -> List[int]: m, n = len(nums1), len(nums2) i = j = 0 ans = [0] * (m + n) for k in range(m + n): if compare(nums1, nums2, i, j): ans[k] = nums1[i] i += 1 else: ans[k] = nums2[j] j += 1 return ans m, n = len(nums1), len(nums2) l, r = max(0, k - n), min(k, m) ans = [0] * k for x in range(l, r + 1): arr1 = f(nums1, x) arr2 = f(nums2, k - x) arr = merge(arr1, arr2) if ans < arr: ans = arr return ans(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !