Split the number N by maximizing the count of subparts divisible by K
Given a numeric string N and an integer K, the task is to split digits of N into subparts such that the number of segments divisible by K is maximized.
Note: We can make any number of vertical cuts between pairs of adjacent digits.
Input: N = 32, K = 4
32 is divisible by 4 but none if its digits are individually divisible, so we don’t perform any splits.
Input: N = 2050, K = 5
2050 can be split into 2, 0, 5, 0 where 0, 5, 0 are divisible by 5.
Input: N = 00001242, K = 3
00001242 can be split into 0, 0, 0, 0, 12, 42 where all the parts are divisible by 3.
To solve the problem mentioned above we will try to use a recursive approach.
- Check if there is a vertical partition between the current character and the next one, if no then we perform recursion again for the next index and update the substring value by concatenating the present character.
- Now, if there is a vertical partition between the current character and the next character, then there exist two cases:
- If the present subStr is divisible by X, then we add 1 because the present subStr is 1 of the possible answer, then recur for the next index and update subStr as an empty string.
- If the present subStr is not divisible by X, then we simply recur for the next index and update subStr as an empty string.
- Return a maximum of the two possible cases mentioned above.
Below is the implementation of the above logic
Please Login to comment...