Solution Notes: This problem can be solved by "brute force", by simply trying to remove each possible cow ID from the line, checking after each one whether it gives the best answer (the longest consecutive block of equal cow IDs). Below is Travis Hance's solution using this idea. Although the running time of this method is O(N^2) (which is plenty fast for the limits in this problem), note that it is possible to solve the problem even faster, in only O(N) time. The idea behind the faster solution is to scan through the array in just one pass, remembering the two most recent distinct IDs you have seen, as well as a count of each one. For example, if the array is 31221254 and we are located at the third "2", then our current state will tell us that we have just scanned across three 2s and two 1s (giving a consecutive block size of 3, if we delete the 1s).

#include <cstdio>

int id[1005];

int get_largest_block(int n, int idignore) {
	int maxBlockSize = 0;

	int curBreed = -1;
	int curSize = 0;
	for(int i = 0; i < n; i++) {
		if(id[i] != idignore) {
			if(curBreed == id[i]) {
			} else {
				curBreed = id[i];
				curSize = 1;
			if(curSize > maxBlockSize)
				maxBlockSize = curSize;

	return maxBlockSize;

int main() {

	int n;
	scanf("%d", &n);
	for(int i = 0; i < n; i++) {
		scanf("%d", &id[i]);

	int ans = 0;
	for(int i = 0; i < n; i++) {
		int size = get_largest_block(n, id[i]);
		if(size > ans)
			ans = size;
	printf("%d\n", ans);