Farmer John's $N$ cows ($1 \le N \le 100{,}000$) share many traits. FJ has narrowed those traits down to a list of only $K$ distinct features ($1 \le K \le 30$). For example, cows with feature #1 might have spots, cows with feature #2 might prefer C over Pascal, and so on.
Each cow is described by a feature ID: a single $K$-bit integer whose binary representation encodes exactly which features the cow has. Reading the binary digits from right (least significant) to left, a $1$ in the $2^{i-1}$ place means the cow exhibits feature $i$. For example, a feature ID of $13$ is $1101$ in binary, so that cow exhibits features $1$, $3$, and $4$, but not feature $2$.
FJ lines the cows up in a row as cows $1 \dots N$ and notices that some contiguous ranges are balanced. A contiguous range of cows $i \dots j$ is balanced when every one of the $K$ features is exhibited by the same number of cows inside that range. Determine the size (number of cows) of the largest balanced range.
The row has $7$ cows with $3$ features. The table below shows the correspondence:
Feature 3: 1 1 1 0 0 1 0
Feature 2: 1 1 1 1 0 0 1
Feature 1: 1 0 1 0 1 0 0
Key: 7 6 7 2 1 4 2
Cow #: 1 2 3 4 5 6 7
In the range from cow #3 to cow #6 (size $4$), each feature is exhibited by exactly $2$ cows:
Feature 3: 1 0 0 1 -> two total
Feature 2: 1 1 0 0 -> two total
Feature 1: 1 0 1 0 -> two total
Key: 7 2 1 4
Cow #: 3 4 5 6