There are n houses evenly lined up on the street, and each house is beautifully painted. You are given a 0-indexed integer array colors of length n, where colors[i] represents the color of the ith house.
Return themaximum distance between two houses with different colors.
The distance between the ith and jth houses is abs(i - j), where
abs(x) is the absolute value of x.

Input: colors =[_**1**_ ,1,1,**_6_**,1,1,1]Output: 3Explanation: In the above image, color 1is blue, and color 6is red.The furthest two houses with different colors are house 0 and house 3.House 0 has color 1, and house 3 has color 6. The distance between them isabs(0-3)=3.Note that houses 3 and 6 can also produce the optimal answer.

Input: colors =[_**1**_ ,8,3,8,_**3**_]Output: 4Explanation: In the above image, color 1is blue, color 8is yellow, and color 3is green.The furthest two houses with different colors are house 0 and house 4.House 0 has color 1, and house 4 has color 3. The distance between them isabs(0-4)=4.
Input: colors =[_**0**_ ,**_1_**]Output: 1Explanation: The furthest two houses with different colors are house 0 and house 1.House 0 has color 0, and house 1 has color 1. The distance between them isabs(0-1)=1.
The answer is the maximum distance between the first house and the last house with a different color, or the last house and the first house with a different color.
classSolution {
publicintmaxDistance(int[] colors) {
int n = colors.length;
int ans = 0;
for (int i = 0; i < n; ++i) {
if (colors[i]!= colors[0]) ans = Math.max(ans, i);
if (colors[i]!= colors[n-1]) ans = Math.max(ans, n-1-i);
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
defmaxDistance(colors):
n = len(colors)
ans =0for i in range(n):
if colors[i] != colors[0]:
ans = max(ans, i)
if colors[i] != colors[-1]:
ans = max(ans, n-1-i)
return ans