Maximize given function by selecting equal length substrings from given Binary Strings
Last Updated :
06 Nov, 2023
Given two binary strings s1 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 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.
Below is the implementation of above approach:
C++
// C++ program for above approach
#include <bits/stdc++.h>
using namespace std;
int dp[1000][1000];
// Function to find longest common substring.
int lcs(string s, string k, int n, int m)
{
for (int i = 0; i <= n; i++) {
for (int j = 0; j <= m; j++) {
if (i == 0 or j == 0) {
dp[i][j] = 0;
}
else if (s[i - 1] == k[j - 1]) {
dp[i][j] = 1 + dp[i - 1][j - 1];
}
else {
dp[i][j] = max(dp[i - 1][j],
dp[i][j - 1]);
}
}
}
// Return the result
return dp[n][m];
}
// Driver Code
int main()
{
string s1 = "1110";
string s2 = "1101";
cout << lcs(s1, s2,
s1.size(), s2.size());
return 0;
}
Java
// Java program for above approach
class GFG{
static int dp[][] = new int[1000][1000];
// Function to find longest common substring.
static int lcs(String s, String k, int n, int m)
{
for (int i = 0; i <= n; i++) {
for (int j = 0; j <= m; j++) {
if (i == 0 || j == 0) {
dp[i][j] = 0;
}
else if (s.charAt(i - 1) == k.charAt(j - 1)) {
dp[i][j] = 1 + dp[i - 1][j - 1];
}
else {
dp[i][j] = Math.max(dp[i - 1][j],
dp[i][j - 1]);
}
}
}
// Return the result
return dp[n][m];
}
// Driver Code
public static void main(String [] args)
{
String s1 = "1110";
String s2 = "1101";
System.out.print(lcs(s1, s2,
s1.length(), s2.length()));
}
}
// This code is contributed by AR_Gaurav
Python3
# Python3 program for above approach
import numpy as np;
dp = np.zeros((1000,1000));
# Function to find longest common substring.
def lcs( s, k, n, m) :
for i in range(n + 1) :
for j in range(m + 1) :
if (i == 0 or j == 0) :
dp[i][j] = 0;
elif (s[i - 1] == k[j - 1]) :
dp[i][j] = 1 + dp[i - 1][j - 1];
else :
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
# Return the result
return dp[n][m];
# Driver Code
if __name__ == "__main__" :
s1 = "1110";
s2 = "1101";
print(lcs(s1, s2,len(s1), len(s2)));
# This code is contributed by AnkThon
C#
// C# program for above approach
using System;
public class GFG{
static int [,]dp = new int[1000,1000];
// Function to find longest common substring.
static int lcs(string s, string k, int n, int m)
{
for (int i = 0; i <= n; i++) {
for (int j = 0; j <= m; j++) {
if (i == 0 || j == 0) {
dp[i, j] = 0;
}
else if (s[i - 1] == k[j - 1]) {
dp[i, j] = 1 + dp[i - 1, j - 1];
}
else {
dp[i, j] = Math.Max(dp[i - 1, j],
dp[i, j - 1]);
}
}
}
// Return the result
return dp[n, m];
}
// Driver Code
public static void Main(string [] args)
{
string s1 = "1110";
string s2 = "1101";
Console.Write(lcs(s1, s2, s1.Length, s2.Length));
}
}
// This code is contributed by AnkThon
JavaScript
<script>
// JavaScript program for above approach
var dp = new Array(1000);
for (var i = 0; i < 1000; i++) {
dp[i] = new Array(1000);
}
// Function to find longest common substring.
function lcs( s, k, n, m)
{
for (var i = 0; i <= n; i++) {
for (var j = 0; j <= m; j++) {
if (i == 0 || j == 0) {
dp[i][j] = 0;
}
else if (s[i - 1] == k[j - 1]) {
dp[i][j] = 1 + dp[i - 1][j - 1];
}
else {
dp[i][j] = Math.max(dp[i - 1][j],
dp[i][j - 1]);
}
}
}
// Return the result
return dp[n][m];
}
// Driver Code
var s1 = "1110";
var s2 = "1101";
document.write(lcs(s1, s2, s1.length, s2.length))
// This code is contributed by AnkThon
</script>
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:
- Take two strings as input: s1 and s2.
- 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.
- Define a function lcs(s1, s2, n, m) that takes s1, s2, n, and m as input.
- If n or m is equal to 0, return 0 as the base case.
- If dp[n][m] is not equal to -1, return dp[n][m].
- If the last characters of s1 and s2 match, then return 1 + lcs(s1, s2, n-1, m-1).
- Otherwise, return the maximum of lcs(s1, s2, n-1, m) and lcs(s1, s2, n, m-1).
- In the main function, call lcs(s1, s2, n, m) and print the result.
Below is the implementation of above approach:
C++
// C++ program for above approach
#include <bits/stdc++.h>
using namespace std;
int dp[1000][1000];
// Function to find longest common substring.
int lcs(string s, string k, int n, int m)
{
// base case
if (n == 0 or m == 0) {
return 0;
}
// if value is already computed
// return that value
if(dp[n][m] != -1)
return dp[n][m];
// if characters at (n-1) and (m-1)th position
// of the strings are equal
if (s[n - 1] == k[m - 1]) {
return dp[n][m] = 1 + lcs(s, k, n - 1, m - 1);
}
// if characters at (n-1) and (m-1)th position
// of the strings are not equal,
// return maximum of LCS of two substrings after
// excluding last character of each string
return dp[n][m] = max(lcs(s, k, n - 1, m),
lcs(s, k, n, m - 1));
}
// Driver Code
int main()
{
string s1 = "1110";
string s2 = "1101";
// initialise dp with -1
memset(dp, -1, sizeof(dp));
cout << lcs(s1, s2,
s1.size(), s2.size());
return 0;
}
// This code is contributed by Chandramani Kumar
Java
import java.util.Arrays;
public class GFG {
static int[][] dp;
// Function to find longest common substring.
static int lcs(String s, String k, int n, int m) {
// base case
if (n == 0 || m == 0) {
return 0;
}
// if value is already computed, return that value
if (dp[n][m] != -1) {
return dp[n][m];
}
// if characters at (n-1) and (m-1)th position
// of the strings are equal
if (s.charAt(n - 1) == k.charAt(m - 1)) {
return dp[n][m] = 1 + lcs(s, k, n - 1, m - 1);
}
// if characters at (n-1) and (m-1)th position
// of the strings are not equal,
// return the maximum of LCS of two substrings after
// excluding the last character of each string
return dp[n][m] = Math.max(lcs(s, k, n - 1, m), lcs(s, k, n, m - 1));
}
// Driver code
public static void main(String[] args) {
String s1 = "1110";
String s2 = "1101";
// initialize dp with -1
dp = new int[s1.length() + 1][s2.length() + 1];
for (int[] row : dp) {
Arrays.fill(row, -1);
}
System.out.println(lcs(s1, s2, s1.length(), s2.length()));
}
}
Python3
# Function to find the longest common substring
def lcs(s, k, n, m):
# Base case
if n == 0 or m == 0:
return 0
# If value is already computed, return that value
if dp[n][m] != -1:
return dp[n][m]
# If characters at (n-1) and (m-1) positions of the strings are equal
if s[n - 1] == k[m - 1]:
dp[n][m] = 1 + lcs(s, k, n - 1, m - 1)
return dp[n][m]
# If characters at (n-1) and (m-1) positions of the strings are not equal,
# return the maximum of LCS of two substrings after excluding the last character of each string
dp[n][m] = max(lcs(s, k, n - 1, m), lcs(s, k, n, m - 1))
return dp[n][m]
# Driver Code
s1 = "1110"
s2 = "1101"
# Initialize dp with -1
dp = [[-1 for _ in range(len(s2) + 1)] for _ in range(len(s1) + 1)]
print(lcs(s1, s2, len(s1), len(s2)))
C#
using System;
public class GFG
{
static int[,] dp;
// Function to find longest common substring.
public static int LCS(string s, string k, int n, int m)
{
// Base case
if (n == 0 || m == 0)
{
return 0;
}
// If value is already computed, return that value
if (dp[n, m] != -1)
return dp[n, m];
// If characters at (n-1) and (m-1)th position of the strings are equal
if (s[n - 1] == k[m - 1])
{
return dp[n, m] = 1 + LCS(s, k, n - 1, m - 1);
}
// If characters at (n-1) and (m-1)th position of the strings are not equal,
// return maximum of LCS of two substrings after excluding the last character of each string
return dp[n, m] = Math.Max(LCS(s, k, n - 1, m), LCS(s, k, n, m - 1));
}
public static void Main(string[] args)
{
string s1 = "1110";
string s2 = "1101";
// Initialize dp with -1
dp = new int[s1.Length + 1, s2.Length + 1];
for (int i = 0; i <= s1.Length; i++)
{
for (int j = 0; j <= s2.Length; j++)
{
dp[i, j] = -1;
}
}
Console.WriteLine(LCS(s1, s2, s1.Length, s2.Length));
}
}
JavaScript
// Function to find longest common substring.
function lcs(s, k, n, m) {
// Initialize dp with -1
const dp = new Array(n + 1).fill().map(() => new Array(m + 1).fill(-1));
// Base case
if (n === 0 || m === 0) {
return 0;
}
// If value is already computed, return that value
if (dp[n][m] !== -1) {
return dp[n][m];
}
// If characters at (n-1) and (m-1)th position of the strings are equal
if (s[n - 1] === k[m - 1]) {
return dp[n][m] = 1 + lcs(s, k, n - 1, m - 1);
}
// If characters at (n-1) and (m-1)th position of the strings are not equal,
// return the maximum of LCS of two substrings after excluding the last character of each string
return dp[n][m] = Math.max(lcs(s, k, n - 1, m),
lcs(s, k, n, m - 1));
}
// Driver Code
function main() {
const s1 = "1110";
const s2 = "1101";
const n = s1.length;
const m = s2.length;
console.log(lcs(s1, s2, n, m));
}
main();
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.
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms
DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort
QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials
Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Bubble Sort Algorithm
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph
Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Data Structures Tutorial
Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Binary Search Algorithm - Iterative and Recursive Implementation
Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm
Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all
Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read
Selection Sort
Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted.First we find the smallest element an
8 min read