I was asked this problem in an OA. I am given an n digit number (n <= 1e7), and a number k (<= n)
I was asked to build the largest possible number using some of these digits (maybe all), such that the largest continuous same digit length is <= k.
Thought a lot but could'nt solve. Now I am curious because the solution isnt available online.
pls help i beg.
can you give a small example / test case plz . i mean how will the value of n and k be given? is it like n = 629 and k = 2 so the ans will 962 like this ?
1112 k = 2 largest num is 1211
First of all, using all digits provided is obviously optimal. To max the number, you should select the maximum possible digit starting from the most significant digit greedily. Now we try to simulate this process.
We always select the largest digit unused. However, if we have already used it continuously for $$$k$$$ times, select a smaller digit instead.
So the answer to
88999999
when $$$k=3$$$ will be99989998
.This is actually not correct. At some point we might get stuck because there is only one type of digit left unused and we have already used $$$k$$$ of it.
So we have to check whether it's possible to complete the number using the rest digits every time we select a digit. Actually, this check can be done in $$$O(1)$$$ time with the following casework.
As explained above, we will get stuck if we have too many digit of one only type. Let the count of the digit that remains the most be $$$a$$$ and the number of times continuously we've currently used it be $$$b$$$. Let the count of rest digits be $$$c$$$. Obviously it is possible to complete the number if and only if $$$a\le kc-b$$$.
So we select digits from the highest bit to the lowest bit greedily. For each place, we select the largest digit that hasn't been continuously used for $$$k$$$ times and that it's possible to complete the number using the digits left.