0-1 Maximal Phase Counter Consider an array of bits, say

1 1 1 0 0 0 0 1 0 0 1 0 1 1 1 1 1 0 1 0


We call a contiguous subarray of length ≥ 5 a phase if at least 85% of the bits are the same and the first/last bits are both equal to the majority bit. Furthermore, we call a phase maximal if it is not a strict subarray of some other phase.

Here are the maximal phases of the above example:

1 1 1 0 0 0 0 1 0 0 1 0 1 1 1 1 1 0 1 0
      -------------
                    -------------
                        -------------


As you can see, there are 3 maximal phases. On the other hand, this

1 1 1 0 0 0 0 1 0 0 1 0 1 1 1 1 1 0 1 0
                        ---------


is not a maximal phase as it is a strict subarray of at least one other phase.

The challenge

Input is a sequence of ≥ 5 bits via STDIN, command line or function argument. The bits may come in as a string or an array.

You are to output a single integer, the number of maximal phases for the array, either printed via STDOUT or returned from a function.

Scoring

This is code-golf so the program in the fewest bytes wins.

Test cases

0 1 0 1 0 -&gt; 0
0 0 0 0 0 -&gt; 1
0 0 0 0 1 0 1 1 1 1 -&gt; 0
0 0 0 0 0 1 0 1 1 1 1 1 -&gt; 2
1 0 0 0 0 0 0 0 0 0 0 0 0 1 0 -&gt; 1
0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0 -&gt; 2
0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 -&gt; 1
0 1 0 1 0 0 1 0 1 0 1 0 0 0 1 1 1 1 0 1 0 0 1 1 0 0 0 1 1 0 -&gt; 0
1 1 1 1 1 0 0 0 0 0 1 1 1 1 1 0 0 1 0 0 0 0 0 0 0 0 1 1 0 1 -&gt; 4
0 1 1 0 0 0 0 0 0 0 0 0 0 0 1 0 1 1 1 1 1 1 1 0 1 0 0 0 0 0 -&gt; 5


Here's the explanation for the last case:

0 1 1 0 0 0 0 0 0 0 0 0 0 0 1 0 1 1 1 1 1 1 1 0 1 0 0 0 0 0
---------------------------
      -------------------------
                            -----------------
                                -----------------
                                              -------------


Fun fact: This challenge came about from a data mining problem with the goal of detecting change in temporal data.
Python 2, 149 bytes

a=input()
l=len(a)
n=p=0
for i in range(l):
 for j in range(l-1,i+3,-1):
  if(j&gt;p)&gt;(.15&lt;sum(a[i:j+1])/(j+1.-i)+a[i]+a[j]&lt;2.85):n+=1;p=j;break
print n


The first loop scans across the array from left to right. Each bit, indexed by i, is checked to see if it could be the first bit in a maximal phase.

This is done by the inner loop, which scans from right to left. If the subarray between i and j is a phase, we increase the counter and move on. Otherwise, we keep going until the subarray becomes too small or j reaches the end of the previous maximal phase.

1 1 1 0 0 0 0 1 0 0 1 0 1 1 1 1 1 0 1 0
i -&gt;                               &lt;- j


Example:

$ python phase.py
[1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0]
3