Given N cash, the sequence of numbers consists of {1, 2, 3, 4, ……..}. The associated fee for selecting a quantity in a sequence is the variety of digits it comprises. (For instance value of selecting 2 is 1 and for 999 is 3), the duty is to print the Most variety of components a sequence can include.
Any aspect from {1, 2, 3, 4, ……..}. can be utilized at most 1 time.
Examples:
Enter: N = 11
Output: 10
Clarification: For N = 11 -> deciding on 1 with value 1, 2 with value 1, 3 with value 1, 4 with value 1, 5 with value 1, 6 with value 1, 7 with value 1, 8 with value 1, 9 with value 1, 10 with value 2.
totalCost = 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 2 = 11.Enter: N = 189
Output: 99
Naive strategy: The essential method to resolve the issue is as follows:
Iterate i from 1 to infinity and calculate the fee for present i if the fee for i is greater than the variety of cash which is N then i – 1 would be the reply.
Time Complexity: O(N * logN)
Auxiliary House: O(1)
Environment friendly Strategy: The above strategy might be optimized primarily based on the next concept:
This Downside might be solved utilizing Binary Search. Quite a lot of digits with given value is a monotonic operate of kind T T T T T F F F F. Final time the operate was true will generate a solution for the Most size of the sequence.
Observe the steps beneath to resolve the issue:
- If the fee required for digits from 1 to mid is lower than equal to N replace low with mid.
- Else excessive with mid – 1 by ignoring the fitting a part of the search area.
- For printing solutions after binary search test whether or not the variety of digits from 1 to excessive is lower than or equal to N if that is true print excessive
- Then test whether or not the variety of digits from 1 to low is lower than or equal to N if that is true print low.
- Lastly, if nothing will get printed from above print 0 for the reason that size of the sequence will probably be 0.
Beneath is the implementation of the above strategy:
C++
|
|
Time Complexity: O(logN2) (first logN is for logN operations of binary search, the second logN is for locating the variety of digits from 1 to N)
Auxiliary House: O(1)
Associated Articles: