Search code examples
algorithmlistbinary-search

Longest sequence with given color


Suppose we have a list of elements with values in Black and White. Is there an O(N) algorithm to find the longest sequence comprising of black elements?

I know that using binary search we can do at O(Nlog(N)). I am wondering if we can do better.


Solution

  • You can keep first value of array and index of it. And assign maxCount and maxIndex to keep where is longest sequence started.

    Create oldValue and assign first value of array 
    Create maxCount variable
    Create maxIndex variable (it should be 0 because we use first value of array)
    
    Move on array - start with 2nd element (because we used first already)
       if new value is equal old value
          go to next element and increase count
       else
          check if count > maxCount
             if so maxCount = count and maxIndex = i
             else count = 0 
       and oldValue = currentValue
    

    Do that until reach the end of array. Also it's O(N). I don't write any code because I believe you should do it yourself. You can ask anything after you tried.