Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit d20d73a

Browse files
committedFeb 22, 2025
Add solution #321
1 parent 2adb177 commit d20d73a

File tree

2 files changed

+64
-0
lines changed

2 files changed

+64
-0
lines changed
 

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -259,6 +259,7 @@
259259
316|[Remove Duplicate Letters](./0316-remove-duplicate-letters.js)|Medium|
260260
318|[Maximum Product of Word Lengths](./0318-maximum-product-of-word-lengths.js)|Medium|
261261
319|[Bulb Switcher](./0319-bulb-switcher.js)|Medium|
262+
321|[Create Maximum Number](./0321-create-maximum-number.js)|Hard|
262263
322|[Coin Change](./0322-coin-change.js)|Medium|
263264
324|[Wiggle Sort II](./0324-wiggle-sort-ii.js)|Medium|
264265
326|[Power of Three](./0326-power-of-three.js)|Easy|
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
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

Comments
 (0)
Please sign in to comment.