Given a positive number N, the target is to find the largest number that can be formed after removing any K digits from N.
Input: N = 6358, K = 1
Input: N = 2589, K = 2
- Iterate a loop K times.
- During every iteration, remove every digit from the current value of N once and store the maximum of all the numbers obtained.
- In order to achieve this, we store the maximum of (N / (i * 10)) * i + (N % i) where i ranges from [1, 10l – 1] where l denotes the number of digits of the current value of N.
- Consider this maximum as the current value of N and proceed to the next iteration and repeat the above step.
- Thus, after every iteration, we have the least digit from the current value of N removed. On repeating the process K times, we obtain the largest number possible.
Let us analyze this approach for N = 6358, K = 1
The different possibilities after removal of every digit once are as follows:
(6358 / 10) * 1 + 6358 % 1 = 635 + 0 = 635
(6358 / 100) * 10 + 6358 % 10 = 630 + 8 = 638
(6358 / 1000) * 100 + 6358 % 100 = 600 + 58 = 658
(6358 / 10000) * 1000 + 6358 % 1000 = 0 + 358 = 358
Below is the implementation of the above approach:
Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.