Gold Balanced Lineup
InterviewTime limit1sMemory limit128 MB
Given N cows each with a K-bit feature ID, find the longest contiguous range where every one of the K features appears the same number of times.
- Level
Medium7 of 10
- Topics
- Hash map, Prefix sum, Bit manipulation, Array
- Solved
- No attempts yet
Problem
Farmer John's cows () share many traits. FJ has narrowed those traits down to a list of only distinct features (). 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 -bit integer whose binary representation encodes exactly which features the cow has. Reading the binary digits from right (least significant) to left, a in the place means the cow exhibits feature . For example, a feature ID of is in binary, so that cow exhibits features , , and , but not feature .
FJ lines the cows up in a row as cows and notices that some contiguous ranges are balanced. A contiguous range of cows is balanced when every one of the features is exhibited by the same number of cows inside that range. Determine the size (number of cows) of the largest balanced range.
Input
- Line : two space-separated integers and .
- Lines : line contains a single -bit integer, the feature ID of cow . Its least-significant bit is if the cow exhibits feature #1, and its most-significant bit is if the cow exhibits feature #.
Output
- A single integer: the number of cows in the largest contiguous balanced range. If no non-empty range is balanced, output .
Hint
The row has cows with 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 ), each feature is exhibited by exactly 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