Given a 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.

Recommended: Please try your approach on {IDE} first, before moving on to the solution.

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.

#competitive programming #mathematical #strings #binary-string #divisibility

Maximum splits in binary string such that each substring is divisible
3.25 GEEK