Online store~30 min2s · 256 MBtarget O(n log n × L) time, O(n) spaceclassic twin: lc-179greedy
A shop prints a voucher code by writing the numbers on n coupon fragments one after another, with no spaces. The best code is the largest number that the fragments can make, and every order of the fragments is allowed.
Several orders can print the same best code, for example when two fragments are 5 and 55. The shop wants to know how many orders of the fragments print the best code. The fragments are told apart by their position in the list.
Write count_best_orders(pieces).
pieces[i] is the number on fragment i, written in decimal with no leading zeros. The number 0 is written as 0.Input: pieces = [12,121,5,55,5]
Output: 6The solution sorts the fragments so that fragment a comes before b when a joined to b is larger than b joined to a. Fragments that tie, with both joins equal, can be swapped without changing the code.
| Sorted position | Fragment | Tied with the one before it |
|---|---|---|
| 0 | 5 |
first fragment |
| 1 | 55 |
yes, 555 equals 555 |
| 2 | 5 |
yes |
| 3 | 12 |
no, 5 then 12 beats 12 then 5 |
| 4 | 121 |
no, 12121 is larger than 12112 |
The best code is 555512121. The group of three tied fragments has 3! = 6 orders, and the other two groups have 1 order each. The answer is 6.
Input: pieces = [3,30,34]
Output: 1The best code is 34330, from the order 34, 3, 30. No two fragments tie, so only one order prints it.
Input: pieces = [0,0,0]
Output: 6Every order prints 000, so all 3! = 6 orders are best.
1 ≤ len(pieces) ≤ 100,0000 ≤ pieces[i] ≤ 10,000,000, written in decimal with no leading zerosTrying every order of 100,000 fragments is far beyond any computer, because 100,000 factorial has hundreds of thousands of digits. Sorting by a pair rule costs about 100,000 times 17 comparisons, and each compares texts of at most 16 digits.