Number of ways to form a number with maximum Ks in it
Given a number N and a digit K, the task is to calculate the number of ways to form a number with the maximum number of Ks in it, where in an operation, two adjacent digits of N that sum up to K are both replaced with K.
Input :N=1454781, K=9
Output : 2
Explanation :9 can occur maximum two times after applying given operation and there are two ways of doing it. Two numbers formed are : 19479 and 14979. 194781 cannot be formed as it contains 9 only once which is not maximum.
Input : N=1007, K=8
Output : 1
Explanation : No operations can be applied on 1007.Thus, the maximum number of 8s that can be present is 0, and there is only one possible such number, which is 1007.
Approach: The following observations help in solving the problem:
- Considering the number as string, substrings of the form “ABAB…” where A+B=K are the only segments of the number that contribute to the answer.
- If the length of the contributing substring is even, there is only one way of applying the operations on them, and thus, they don’t contribute to the answer. For example, if the substring is “ABAB”, it can be changed only into “KK” to get the maximum number of K’s in the final number
- Otherwise, there will ⌈L/2⌉ ways to get the maximum number of Ks, where L is the length of the substrings. For example, if the substring is “ABABA”, this can be turned into the following:
Follow the steps below to solve the problem:
- Convert N into a string, say S.
- Initialize a variable ans to 1, to store the final answer.
- Traverse the string S and for each current index i, do the following:
- Initialize a variable count to 1, to store the length of the current answer.
- Loop while i is less than length of S, and the sum of the digits at S[i] and S[i-1] is equal to K, and do the following:
- Increment i.
- Increment count.
- If count is odd, update ans as ans*(count+1)/2.
- Return ans.
Below is the implementation of the above approach:
Time Complexity: O(Log10N), since, the number of digits in N is Log10N
Auxiliary Space: O(1)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.