Table of Contents
Example
illustrate
Naive method
Efficient method
idea
Implementation
Output
in conclusion
Home Backend Development C++ Maximize the given function by selecting equal length substrings from the given binary string

Maximize the given function by selecting equal length substrings from the given binary string

Aug 28, 2023 am 09:49 AM
substring binary string maximize

Maximize the given function by selecting equal length substrings from the given binary string

Given two binary strings str1 and str2 of the same length, we have to maximize the given function by selecting substrings from the given strings of the same length value. The given function is like this -

fun(str1, str2) = (len(substring))/(2^xor(sub1, sub2)).

Here, len(substring) is the length of the first substring, and xor(sub1, sub2) is the XOR of the given substring, which is possible since they are binary strings.

Example

Input1: string str1 = 10110 & string str2 = 11101 
Copy after login
Output: 3
Copy after login

illustrate

We could choose many different sets of strings to find the solution, but choosing "101" from both strings will XOR zero, which will cause the function to return the maximum value.

Input2: string str1 = 11111, string str2 = 10001 
Copy after login
Output: 1 
Copy after login

illustrate

We can select "1" as substring which will result in this output and if we select any other string it will result in lower value.

Naive method

In this method, we will find all substrings and then compare them to find the solution, but this solution is not efficient and will take a lot of time and space complexity.

The average time complexity of generating substrings of length x is N^2, and then comparing each substring will cost N^2 more. Additionally, we also have to find the XOR of the given substring, which also costs an additional factor of N, which means N^5 will be the time complexity of the above code, which is very inefficient.

Efficient method

idea

The idea here comes from the simple observation that as the XOR value gets higher, it always reduces the answer. Therefore, in order to maximize the function return value, we must reduce the XOR value as much as possible.

In the case where both substrings are zero, the minimum XOR value that can be achieved is zero. Therefore, this problem is actually derived from the longest common substring problem.

When the XOR is zero, the dividend part is 1, so the final answer will be the length of the largest common substring.

Implementation

We have seen the idea to solve the problem, let’s look at the steps to implement the code -

  • We will create a function that will accept two given strings as input and return an integer value, which will be our final result.

  • In the function, we first get the length of the string and then create a 2D vector of the size multiplied by the given string.

  • We will use nested for loops to iterate through the string and get the largest common substring.

  • On each iteration we will check if the current indices of the two strings match, then we will get the value from the vector of the last index of the two strings.

  • Otherwise, we just set the current index of the vector to zero.

  • Additionally, we will maintain a variable to maintain a count of the maximum length of the common substring.

  • Finally, we will return the answer and print it in the main function.

Example

#include <bits/stdc++.h>
using namespace std;
// function to get the result
int result(string str1, string str2){
   int n = str1.length(); // size of the first string
   int m = str2.length(); // size of the second string   
   
   // creating vector to store the dynamic programming results 
   vector<vector<int>>dp(n+1, vector<int>(m+1)); 
   int ans = 0; // variable to store the result 
   
   // traversing over the strings using nested for loops 
   for (int i = 1; i <= n; i++){
      for (int j = 1; j <= m; j++){ 
      
         // if current elements of both the string are equal 
         if (str1[i - 1] == str2[j - 1]){
            // getting one maximum of the last two 
            dp[i][j] = 1 + dp[i - 1][j - 1];
            ans = max(ans, dp[i][j]);
         }
      }
   }
   return ans; // return the final answer or count 
} 
int main(){
   string str1 = "10110";
   string str2 = "11101"; 
   
   // calling the function
   cout<<"The maximum score for a given function by selecting equal length substrings from given binary strings is "<< result(str1,str2)<<endl;
   return 0;
}
Copy after login

Output

The maximum score for a given function by selecting equal length substrings from given binary strings is 3
Copy after login

Time and space complexity

The time complexity of the above code is O(N^2) because we use nested for loops and iterate N times each time.

Since we use a two-dimensional array to store elements, the space complexity of the above code is O(N^2).

in conclusion

In this tutorial, we code to implement the maximum score of a given function by selecting substrings of equal length from a given binary string. We've already discussed this naive approach, which is extremely inefficient. Depending on the given function, the value of the XOR is smaller, so we make the XOR zero by getting the longest common substring in O(N^2) time complexity.

The above is the detailed content of Maximize the given function by selecting equal length substrings from the given binary string. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use the LOCATE function in MySQL to find the position of a substring in a string How to use the LOCATE function in MySQL to find the position of a substring in a string Jul 25, 2023 am 09:45 AM

How to use the LOCATE function in MySQL to find the position of a substring in a string. In MySQL, there are many functions that can be used to process strings. Among them, the LOCATE function is a very useful function that can be used to find the position of a substring in a string. The syntax of the LOCATE function is as follows: LOCATE(substring,string,[position]) where substring is the substring to be found and string is the substring to be found.

Count the number of occurrences of a substring recursively in Java Count the number of occurrences of a substring recursively in Java Sep 17, 2023 pm 07:49 PM

Given two strings str_1 and str_2. The goal is to count the number of occurrences of substring str2 in string str1 using a recursive procedure. A recursive function is a function that calls itself within its definition. If str1 is "Iknowthatyouknowthatiknow" and str2 is "know" the number of occurrences is -3. Let us understand through examples. For example, input str1="TPisTPareTPamTP", str2="TP"; output Countofoccurrencesofasubstringrecursi

The strtok_r() function is a function in C language. Its function is to split a string into a series of substrings. The strtok_r() function is a function in C language. Its function is to split a string into a series of substrings. Aug 26, 2023 am 09:45 AM

This function is similar to the strtok() function. The only key difference is _r, which is called a reentrant function. Reentrant functions are functions that can be interrupted during execution. This type of function can be used to resume execution. Therefore, reentrant functions are thread-safe, which means they can be safely interrupted by threads without causing any damage. The strtok_r() function has an extra parameter called context. This way the function can be restored in the correct location. The syntax of the strtok_r() function is as follows: #include<string.h>char*strtok_r(char*string,constchar*limiter,char**

Written in C++, find the number of unique permutations of a binary string starting with 1 Written in C++, find the number of unique permutations of a binary string starting with 1 Sep 05, 2023 am 09:01 AM

In the given problem, we are given a string consisting of 0 and 1; we need to find the total number of all permutations starting with 1. Since the answer may be a huge number, we take it modulo 1000000007 and output it. Input:str="10101001001"Output:210Input:str="101110011"Output:56 We will solve this problem by applying some combinatorial mathematics and setting up some formulas. Solution Method In this method we will count the number of 0's and 1's. Now suppose n is the number of 1's that appear in our string and m is the number of 0's that appear in our string

Longest non-increasing subsequence in a binary string Longest non-increasing subsequence in a binary string Sep 07, 2023 pm 11:13 PM

In this problem, we need to find the longest non-increasing subsequence of a given string. Non-increasing means that the characters are either the same or in descending order. Since binary strings only contain "0" and "1", the resulting string should either start with "1" and end with "0", or start and end with "0" or "1". To solve this problem, we will count the prefix "1" and suffix "0" at each position of the string and find the maximum sum of prefix "1" and suffix "0". Problem Statement - We are given a binary string str. We need to find the longest non-increasing subsequence from the given string. Example Input–str="010100"Output–4 illustrates the longest non-recursive

In PHP, the function of pack() function is to convert data into binary string In PHP, the function of pack() function is to convert data into binary string Aug 31, 2023 pm 02:05 PM

The pack() function packs data into a binary string. Syntax pack(format,args) Parameters format - the format to use. The following are possible values ​​- a - NUL padded string A - space padded string h - hexadecimal string, low nibble first H - hexadecimal string, high nibble first c - signed char C - unsigned char s - signed short (always 16 bits, machine byte order) S - unsigned short (always 16 bits, machine byte order) n - unsigned short (always 16 bits, big endian byte order) v - unsigned short (always 16 bits, little endian byte order) i - signed integer (depends on machine size and byte order) I - None signed integer (depending on

PHP returns the string from the start position to the end position of a string in another string PHP returns the string from the start position to the end position of a string in another string Mar 21, 2024 am 10:31 AM

This article will explain in detail how PHP returns the string from the start position to the end position of a string in another string. The editor thinks it is quite practical, so I share it with you as a reference. I hope you will finish reading this article. You can gain something from this article. Use the substr() function in PHP to extract substrings from a string. The substr() function can extract characters within a specified range from a string. The syntax is as follows: substr(string,start,length) where: string: the original string from which the substring is to be extracted. start: The index of the starting position of the substring (starting from 0). length (optional): The length of the substring. If not specified, then

PHP Regular Expression: How to extract specific characters from a string to a substring at the end PHP Regular Expression: How to extract specific characters from a string to a substring at the end Jun 22, 2023 pm 05:33 PM

Regular expressions are a powerful text processing tool that can be used to match strings in specific patterns. In PHP, regular expressions are commonly used in string processing, form validation, search and replacement, etc. This article will introduce how to use PHP's regular expressions to extract specific characters from a string to the substring at the end. First, let's look at an example. Suppose we have a string $str that contains multiple URLs starting with "http://" and we want to extract these URLs and store them in a

See all articles