Finding a substring, with some additional conditions

后端 未结 3 1244
太阳男子
太阳男子 2021-02-03 13:53

I\'m given a string which looks like this:

1011010100

And my task is to find the length of a substring which number of nulls is always <= nu

3条回答
  •  心在旅途
    2021-02-03 14:38

    Here goes my algorithm:

    Start from right side:

     1. if you find 0 increment the value of count
     2. if you find 1 decrement the count
    

    Store these values in an array i.e. v[]. e.g.

    a[] = {1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0, 1}
    
    v[] = {0, 1, 0,-1, 0, 1, 0, 1, 2, 1, 2, 1, 0, -1}
    

    Now the problem reduces to find indexes from V i.e. i, j such that v[i] < v[j] and i.

    proof:

    if you see here i=0 and j=11 is the possible answer and values are v[i]=0, v[j]=1. This means that till j we have one 0 extra in the string and as the v[i]=0 that means from i to j window size the extra 0 is cancelled by putting extra 1. Hence the answer.

    Hope it helps. please let me know if you have doubt. Thanks.

提交回复
热议问题