Table of Contents
Problem Statement
Example Example 2
Output obtained is: 1
Explanation
Approach
Algorithm
Example: C program
Output
in conclusion
Home Backend Development C++ Maximum possible balanced binary substring splitting, taking at most k

Maximum possible balanced binary substring splitting, taking at most k

Aug 29, 2023 am 09:41 AM
substring Split balanced binary

Maximum possible balanced binary substring splitting, taking at most k

The array in the C programming language has a fixed size, which means that once the size is specified, it cannot be changed; you can neither shrink it or extend it.

As we know, an array is a set of elements of the same data type, which are stored in a contiguous memory area.

Given an array of values ​​v[] and a binary array a[]. The objective is to use as many k coins to divide the binary array as much as is possible while ensuring that each segment has an equal amount of 0s and 1s. i and j are the neighboring indices of the split segment, and the cost of each split is (v[i] - v[j])2.

Problem Statement

Implement a program that finds the largest possible balanced binary substring split, costing at most k.

Example Example 1

Let the Input array be: 
a: [1,0,0, 1, 0, 0, 1, 1]
The given values be: 
v: [7, 8, 9, 10, 11, 12,13,14]
K: 1
Copy after login

Output obtained is: 1

Explanation

Since the value of K is 1, we can make a cut between the first and second index.

In this case, [0, 1] and [0, 0, 1, 1] are the balanced binary substrings of the final result.

Making this cut will cost (8 - 9)^ 2 = 1, and 1 = 1.

Example Example 2

Let the Input array be: 
a: [1,0 1, 0, 1, 1, 0,0]
The given values be: 
v: [2, 4, 7, 10, 11, 12, 13, 14]
K: 14
Copy after login
Output obtained is: 2
Copy after login

Explanation

The first cut will be made between the first and second index that is 4 and 7, costing us (4 - 7)^2 = 9 and the second cut will be made between the third and fourth index that is 7 and 10 , costing us (7 - 10)^ 2 = 9. No more cuts are possible at this time. The balanced binary substrings in this case that would arise are [1, 0], [1, 0], and [1, 1 , 0, 0].

Approach

In order to find maximum possible balanced binary substring splits with at most cost k, we take the following methodology.

Here we take a top-down approach to solve this problem and to find maximum possible balanced binary substring splits with at most cost k.

Use the top-down approach, or more commonly known as the dynamic programming approach. The main advantage of dynamic programming is the improved efficiency of simple recursion. Dynamic programming can be used to optimize any recursive solution that involves repeated calls to the same input. To avoid recomputing the results of subproblems later, the idea is to store them. With this simple optimization, the time complexity is reduced from polynomial to exponential.

Algorithm

The algorithm to find maximum possible balanced binary substring splits with at most cost K is given below.

  • Step One - Start

  • Step 2 - Define a two-dimensional matrix m

  • Step 3 - Define a function to find the largest possible balanced binary substring split.

  • Step 4 − Define integer variables zeroCount to count the number of zeros and oneCount to count the number of ones respectively

  • Step 5 − Define an integer variable cntSplits to calculate the number of splits

  • Step 6 - Iterate over the given array a

  • Step 7 − check whether the number of zeros is equal to the number of ones, then store the maximum feasible one

  • Step 8 - Assume the index is at position 0, then find out if it is 1 or 0, then increment the count

  • Step 9 − set the cntSplits to zero, if count of one and count of zero is unequal.

  • Step 10 - Store the resulting values ​​in the matrix

  • Step 11 − Print the desired result obtained

  • Step 12 − Stop

Example: C program

This is a C program implementation of the above algorithm for finding the largest possible balanced binary substring split, costing at most k.

#include <stdio.h>
#include <limits.h>
#include <string.h>
//Define a two-dimensional matrix m
int m[1001][1001];

//Define a function to find maximum possible //balanced binary substring splits
int maxSplits(int a[], int v[], int k, int s) {
   if (k < 0) {
      return INT_MIN;
   }
   if (m[k][s] != -1) {
      return m[k][s];
   }
   
   //Define integer variables to count the number of zeros and ones 
   // Define an integer variable to count the //number of splits
   int zeroCount = 0, oneCount = 0;
   int cntSplits = 0;
   int i;
   
   //Iterating through the given array a
   for (i = s - 1; i > 0; i--) {
      a[i] == 0 ? zeroCount++ : oneCount++;
      
   // check whether the number of zeros is equal to the number of ones, then store the maximum feasible one
      if (zeroCount == oneCount) {
         cntSplits = cntSplits > (1 + maxSplits(a, v, k - (v[i] - v[i - 1]) * (v[i] - v[i - 1]), i)) ? cntSplits : (1 + maxSplits(a, v, k - (v[i] - v[i - 1]) * (v[i] - v[i - 1]), i));
      }
   }
   
   //Suppose the index is at the position 0, then find whether it is a one or a zero. then increment the count
   if (i == 0) {
      a[0] == 0 ? zeroCount++ : oneCount++;
      
   // set the cntSplits to zero , if count of one and count of zero is unequal.
      if (zeroCount != oneCount) {
         cntSplits = 0;
      }
   }
   
   // store the resultant value in the matrix
   return m[k][s] = cntSplits;
}
int main() {
   int a[] = { 1, 0, 0, 1, 0, 0, 1, 1 };
   int v[] = { 7, 8, 9, 10, 11, 12, 13, 14 };
   int k = 1;
   int s = sizeof(a) / sizeof(a[0]);
   
   //To assign a specific value to a block of memory, we use the memset() function.
   memset(m, -1, sizeof(m));
   printf("%d\n", maxSplits(a, v, k, s));
   return 0;
}
Copy after login

Output

1
Copy after login

in conclusion

Similarly, we can find possible balanced binary substring splits that cost at most K.

In this paper, the challenge of getting a program to find the largest possible balanced binary substring splitting at most cost K is addressed.

C programming code is provided here along with an algorithm to find the largest possible balanced binary substring split, costing at most K.

The above is the detailed content of Maximum possible balanced binary substring splitting, taking at most k. 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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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)

Get started quickly: JSON array merging and splitting techniques in Java. Get started quickly: JSON array merging and splitting techniques in Java. Sep 06, 2023 am 10:21 AM

Get started quickly: JSON array merging and splitting techniques in Java In modern software development, data format and transmission have become increasingly important. Among them, JSON (JavaScriptObjectNotation) is a commonly used data format, especially suitable for front-end and back-end interaction and data storage. In Java development, we often need to deal with JSON objects and JSON arrays. This article explains how to merge and split JSON arrays in Java, along with tips and examples for implementing these operations.

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**

How to use PHP ZipArchive to merge and split multiple compressed packages? How to use PHP ZipArchive to merge and split multiple compressed packages? Jul 21, 2023 am 10:17 AM

How to use PHPZipArchive to merge and split multiple compressed packages? Overview: During the development process, sometimes we need to merge multiple compressed packages into one, or split a compressed package into multiple ones. PHP provides the ZipArchive extension to easily complete these operations. This article will introduce how to use PHPZipArchive to merge and split multiple compressed packages. Merging multiple archives First, we need to create a new archive and open it. Then, the loop traversal needs to be

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

Palindromic substring query in C++ Palindromic substring query in C++ Sep 22, 2023 am 09:05 AM

In this tutorial, we need to solve a palindrome substring query for a given string. Solving palindrome substring queries is much more complex than solving regular queries in C++. It requires more complex code and logic. In this tutorial, we have provided string str and Q substring [L...R] queries, each of which has two values ​​L and R. Our goal is to write a program that solves a query to determine if substring[L...R] is a palindrome. We have to determine whether the substring formed in the range L to R is a palindrome to solve each query. For example-Let'sinput"abbbabaaaba"asourinputstring.Thequer

See all articles