Maximize [length(X)/2^(XOR(X, Y))] by choosing substrings X and Y from string A and B respectively
Given two binary strings A and B of size N and M respectively, the task is to maximize the value of the length of (X) / 2XOR(X, Y) by choosing two substrings X and Y of equal length from the given string A and B respectively.
Input: A = “0110”, B = “1101”
Choose the substring “110” and “110” from the string A and B respectively. The value of the expression of length(X) / 2XOR(X, Y) is 3 / 20 = 3, which is maximum among all possible combinations.
Input: A = “1111”, B = “0000”
Approach: The given problem can be solved by observing the expression that it needs to be maximized, therefore the denominator must be minimum, and to minimize it the value of Bitwise XOR of the substrings X and Y must be minimum i.e., zero and to make the value of Bitwise XOR as zero, the two substrings must be same. Therefore, the problem reduces to finding the Longest Common Substring of both the strings A and B. Follow the steps below to solve the problem:
- Initialize a 2D array, say LCSuff[M + 1][N + 1] to store the lengths of the longest common suffixes of the substrings.
- Initialize a variable, say result as 0 to store the result maximum value of the given expression.
- Iterate over the range [0, M] using the variable i and nested iterate over the range [0, N] using the variable j and perform the following steps:
- If i equals 0 or j equals 0, then update the value of LCSSuff[i][j] equals 0.
- Otherwise, if the value of A[i – 1] equals A[j – 1] then update the value of LCSSuff[i][j] as LCSSuff[i – 1][j – 1] + 1 and update the value of result as the maximum of result and LCSSuff[i][j].
- Otherwise, update the value of LCSSuff[i][j] to 0.
- After completing the above steps, print the value of result as the result.
Below is the implementation of the above approach:
Time Complexity: O(M*N)
Auxiliary Space: O(M*N)