VOOZH about

URL: https://www.geeksforgeeks.org/dsa/maximize-given-function-by-selecting-equal-length-substrings-from-given-binary-strings/

⇱ Maximize given function by selecting equal length substrings from given Binary Strings - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Maximize given function by selecting equal length substrings from given Binary Strings

Last Updated : 23 Jul, 2025

Given two binary stringss1 and s2. The task is to choose substring from s1 and s2 say sub1 and sub2 of equal length such that it maximizes the function:

fun(s1, s2) = len(sub1) / (2xor(sub1, sub2))

Examples:

Input: s1= "1101", s2= "1110"
Output: 3
Explanation: Below are the substrings chosen from s1 and s2
Substring chosen from s1 -> "110"
Substring chosen from s2 -> "110"
Therefore, fun(s1, s2) = 3/ (2xor(110, 110)) = 3, which is maximum possible. 

Input: s1= "1111", s2= "1000"
Output: 1

Approach: In order to maximize the given function large substrings needed to be chosen with minimum XOR. To minimize the denominator, choose substrings in a way such thatXOR of sub1 and sub2 is always 0 so that the denominator term will always be 1 (20). So for that, find the longest common substring from the two strings s1 and s2, and print its length that would be the required answer. 

Below is the implementation of above approach:


Output
3

Time Complexity: O(N*M), where N is the size of s1 and M is the size of s2.

Auxiliary Space: O(N*M), where N is the size of s1 and M is the size of s2.

Approach2: Using memoised version of dynamic programming

In order to maximize the given function large substrings needed to be chosen with minimum XOR. To minimize the denominator, choose substrings in a way such that XOR of sub1 and sub2 is always 0 so that the denominator term will always be 1 (20). So for that, find the longest common substring from the two strings s1 and s2, and print its length that would be the required answer.

To find longest common substring we will go with memoisation approach.

Algorithm:

  1.    Take two strings as input: s1 and s2.
  2.    Initialize a 2D array dp of size n+1 by m+1 with -1, where n is the length of s1 and m is the length of s2.
  3.    Define a function lcs(s1, s2, n, m) that takes s1, s2, n, and m as input.
  4.    If n or m is equal to 0, return 0 as the base case.
  5.    If dp[n][m] is not equal to -1, return dp[n][m].
  6.    If the last characters of s1 and s2 match, then return 1 + lcs(s1, s2, n-1, m-1).
  7.    Otherwise, return the maximum of lcs(s1, s2, n-1, m) and lcs(s1, s2, n, m-1).
  8.    In the main function, call lcs(s1, s2, n, m) and print the result.

Below is the implementation of above approach:


Output
3

Time Complexity: O(N*M), where N is the size of s1 and M is the size of s2.
Auxiliary Space: O(N*M), where N is the size of s1 and M is the size of s2.

Comment
Article Tags: