Find the longest positive substrings in a binary string

Suppose I have a type string 100110001010001. I would like to find a substring that:

  • as long as possible
  • have a total positive amount> 0

So, the longest substrings that have more than 1s than 0s .

For example, for the line above, 100110001010001it would be:[10011]000[101]000[1]

In fact, it is satisfactory to find the total length of such in this case: 9.

Unfortunately, I have no idea how this can be done not with brute force. Any ideas please?

+4
source share
2 answers

Dynamic programming.

. , . , , . , (N-1, N-2, N-3) .. N- ( a, b), . , .

, , , , a b. . 1 a, b, a, b. , ?

, , . b. , .

:

N = length(string);
Nones = countones(string);
Nzeros = N - Nones;
if(Nones > Nzeroes)
   return string

vector<int> cuta;
vector<int> cutb;
int besta = Nones - Nzeros;
int bestb = Nones - Nzeros;

cuta.push_back(besta);
cutb.push_back(bestb);
bestia = 0;
bestib = 0;

for(i=0;i<N;i++)
{
   cuta.push_back( string[i] == 1 ? cuta.back() - 1 : cuta.back() +1);
   cutb.push_back( string[N-i-1] == 1 ? cutb.back() -1 : cutb.back()+1);

   if(cuta.back() > besta)
   {
      besta = cuta.back();
      bestia = i;
   }
  if(cutb.back() > bestb)
  {
    bestb = cutb.back();
    bestib = i;
  }

   // checks, is a cut from wholly from a or b going to send us positive
   if(besta == 1)
      answer = substring(string, bestia, N);
   if(bestb == 1)
      answer = substring(string, 0, N - bestib);

   // if not, is a combined cut from current position to the
   // the peak in the other distribution going to send us positive?
   if(Nones - Nzeros + besta + cutb.back() == 1)
  {
     answer = substring(string, bestai, N - i);
  }
  if(Nones - Nzeros + cuta.back() + bestb == 1)
  {
      answer = substring(string, i, N - bestbi);
  }

}
/*if we get here the string was all zeros and no positive substring */

, , - , .

0

, . , " ", : , (1) ( ), (2) , (3) , ( ).

(3), (1) (2). , , O(n log n) time O(n) ( O(n) , . : ). O(n^2) O(n) .

, , s[i], -1. , node , , node. ( s[a] s[b] , , b a.) , node.

, , leftmost-index-of-lower-value, node , , ; - , , .

, .

, f(i) i. f(i) , j, f(j-1).

0

Source: https://habr.com/ru/post/1657127/


All Articles