classSolution{public:intmaxDistance(vector<int>&colors){// The maximum distance always includes either the first or the last house.constintn=colors.size();inti=0;// the leftmost index, where colors[i] != colors[-1]intj=n-1;// the rightmost index, where colors[j] != colors[0]while(colors[i]==colors.back())++i;while(colors[j]==colors.front())--j;returnmax(n-1-i,j);}};
1 2 3 4 5 6 7 8 9101112
classSolution{publicintmaxDistance(int[]colors){finalintn=colors.length;inti=0;// the leftmost index, where colors[i] != colors[n - 1]intj=n-1;// the rightmost index, where colors[j] != colors[0]while(colors[i]==colors[n-1])++i;while(colors[j]==colors[0])--j;returnMath.max(n-1-i,j);}}
1 2 3 4 5 6 7 8 91011
classSolution:defmaxDistance(self,colors:list[int])->int:# The maximum distance always includes either the first or the last house.n=len(colors)i=0# the leftmost index, where colors[i] != colors[-1]j=n-1# the rightmost index, where colors[j] != colors[0]whilecolors[i]==colors[-1]:i+=1whilecolors[j]==colors[0]:j-=1returnmax(n-1-i,j)