Longest Subsequence from a numeric String divisible by K
Given an integer K and a numeric string str, the task is to find the longest subsequence from the given string which is divisible by K.
Input: str = “121400”, K = 8
Since the whole string is divisible by 8, the entire string is the answer.
Input: str: “7675437”, K = 64
The longest subsequence from the string which is divisible by 64, is “64” itself.
Approach: The idea is to find all subsequences of the given string and for each subsequence, check if its integer representation is divisible by K or not. Follow the steps below to solve the problem:
- Traverse the string. For every character encountered, two possibilities exists.
- Either consider the current character in the subsequence or not. For both the cases, proceed to the next characters of the string and find the longest subsequence that is divisible by K.
- Compare the longest subsequences obtained above with the current maximum length of longest subsequence and update accordingly.
- Repeat the above steps for every character of the string and finally, print the maximum length obtained.
Below is the implementation of the above approach.
Time Complexity: O(N * 2N)
Auxiliary Space: O(1)
My Personal Notes arrow_drop_up
Please Login to comment...