Given binary string str, the task is to calculate the maximum possible splits possible to make each substring divisible by a given odd number K. Examples:
Input: str = “110111001”, K = 9 Output: 2 Explanation: The two possible substrings are “11011” and “1001”. The equivalent decimal values are 27 and 9 respectively which are divisible by 9. Input: str = “10111001”, K = 5 Output: 2 Explanation: The two possible substrings are “101” and “11001”. The equivalent decimal values are 5 and 25 respectively which are divisible by 5.
Approach: In order to solve this problem, we traverse from the end of the string and generate the sum of the length traversed. As soon as the sum is divisible by K, we increase the count by 1 and reset sum to 0 and traverse forward and repeat the same process. On full traversal of the string, if sum has been reset to 0, then the value of the count gives the required maximum possible splits. Otherwise, print “Not Possible” as all segments are not divisible by K. Below code is the implementation of the above approach:
Please Login to comment...