FJ has N cows (1≤N≤100000) standing along a long one-dimensional fence. Cow i stands at position xi (integer in 0…1000000000) and has breed bi (1…8). No two cows share a position.
FJ wants a photo of a contiguous interval of cows. Every breed that appears in the photo must appear the same number of times (for example, 27 of breed 1 and 27 of breed 3 is fine, but 9 of breed 1 and 10 of breed 3 is not). At least K breeds (K≥2) must appear.
Find the maximum photo size, defined as the difference between the largest and smallest positions among cows in the photo. If no valid photo exists, output −1.
One integer: the maximum fair photo size, or −1 if none exists.
Sort by position, then check each contiguous interval for equal per-breed counts.