Given two numbers N and D. The task is to find out the largest number smaller than or equal to N which contains the maximum number of trailing nines and the difference between N and the number should not be greater than D.
Input: N = 1029, D = 102 Output: 999 1029 has 1 trailing nine while 999 has three trailing nine.Also 1029-999 = 30(which is less than 102). Input: N = 10281, D = 1 Output: 10281
A naive approach will be to iterate from N till N-D and find the number with the largest number of trailing nines.
An efficient approach can be found by some key observations. One key observation for this problem is that the largest number smaller than N ending with at least say(K) nines is
[n – (n MOD 10^k) – 1]
Traverse all possible values of k starting from total no of digits of N to 1, and check whether d > n%. If no such value is obtained, the final answer will be N itself. Otherwise, check for the answer using the above observation.
Below is the implementation of the above approach.
Time Complexity:O(no of digits)
- Largest even digit number not greater than N
- Largest number not greater than N all the digits of which are odd
- Largest number not greater than N which can become prime after rearranging its digits
- Find the largest number smaller than integer N with maximum number of set bits
- Largest number dividing maximum number of elements in the array
- Largest number less than N with digit sum greater than the digit sum of N
- Count number of trailing zeros in Binary representation of a number using Bitset
- Count of Array elements greater than or equal to twice the Median of K trailing Array elements
- Number of trailing zeros in N * (N - 2) * (N - 4)*....
- Permutation of a string with maximum number of characters greater than its adjacent characters
- Largest subsequence having GCD greater than 1
- Trailing number of 0s in product of two factorials
- Count number of trailing zeros in (1^1)*(2^2)*(3^3)*(4^4)*..
- Smallest number divisible by n and has at-least k trailing zeros
- Number of trailing zeroes in base B representation of N!
- Smallest number with at least n trailing zeroes in factorial
- Find the smallest number X such that X! contains at least Y trailing zeros.
- Count trailing zeroes in factorial of a number
- Count number of trailing zeros in product of array
- Check whether all the rotations of a given number is greater than or equal to the given number or not