https://edabit.com/challenge/7vowiHDR5oYksAjqQ
Write a function that makes the first number as large as possible by swapping out its digits for digits in the second number.
To illustrate:
maxPossible(9328, 456) ➞ 9658 // 9658 is the largest possible number built from swaps from 456. // 3 replaced with 6 and 2 replaced with 5.
Examples
maxPossible(523, 76) ➞ 763 maxPossible(9132, 5564) ➞ 9655 maxPossible(8732, 91255) ➞ 9755
Notes
- Each digit in the second number can only be used once.
- Zero to all digits in the second number may be used.
Solution:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | function maxPossible(n1, n2) { let sol = ""; let arrOne = [...n1.toString()].map((num) => parseInt(num)); let arrTwo = [...n2.toString()].map((num) => parseInt(num)); arrTwo.sort((a, b) => b - a); for (let i in arrOne) { if (arrOne[i] < arrTwo[0]) { sol += arrTwo[0]; arrTwo.shift(); } else { sol += arrOne[i]; } } return parseInt(sol); } |
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.