|
| 1 | +/** |
| 2 | + * 321. Create Maximum Number |
| 3 | + * https://leetcode.com/problems/create-maximum-number/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * You are given two integer arrays nums1 and nums2 of lengths m and n respectively. |
| 7 | + * nums1 and nums2 represent the digits of two numbers. You are also given an integer k. |
| 8 | + * |
| 9 | + * Create the maximum number of length k <= m + n from digits of the two numbers. The |
| 10 | + * relative order of the digits from the same array must be preserved. |
| 11 | + * |
| 12 | + * Return an array of the k digits representing the answer. |
| 13 | + */ |
| 14 | + |
| 15 | +/** |
| 16 | + * @param {number[]} nums1 |
| 17 | + * @param {number[]} nums2 |
| 18 | + * @param {number} k |
| 19 | + * @return {number[]} |
| 20 | + */ |
| 21 | +var maxNumber = function(nums1, nums2, k) { |
| 22 | + const m = nums1.length; |
| 23 | + const n = nums2.length; |
| 24 | + let result = new Array(k).fill(0); |
| 25 | + |
| 26 | + for (let i = Math.max(0, k - n); i <= Math.min(k, m); i++) { |
| 27 | + if (i + n < k) continue; |
| 28 | + const candidate = merge( |
| 29 | + getMaxSubsequence(nums1, i), |
| 30 | + getMaxSubsequence(nums2, k - i), |
| 31 | + ); |
| 32 | + result = candidate > result ? candidate : result; |
| 33 | + } |
| 34 | + |
| 35 | + return result; |
| 36 | + |
| 37 | + function getMaxSubsequence(nums, count) { |
| 38 | + const stack = []; |
| 39 | + let removeIndex = nums.length - count; |
| 40 | + |
| 41 | + nums.forEach(n => { |
| 42 | + while (stack.length && stack[stack.length - 1] < n && removeIndex) { |
| 43 | + stack.pop(); |
| 44 | + removeIndex--; |
| 45 | + } |
| 46 | + stack.push(n); |
| 47 | + }); |
| 48 | + |
| 49 | + return stack.slice(0, count); |
| 50 | + } |
| 51 | + |
| 52 | + function merge(a1, a2) { |
| 53 | + const result = []; |
| 54 | + |
| 55 | + while (a1.length || a2.length) { |
| 56 | + const compare = a1 > a2 ? a1 : a2; |
| 57 | + result.push(compare[0]); |
| 58 | + compare.shift(); |
| 59 | + } |
| 60 | + |
| 61 | + return result; |
| 62 | + } |
| 63 | +}; |
0 commit comments