Leetcode 2078. Two Furthest Houses With Different Colors
You are given an array colors
where colors[i]
is the color of the i-th
house. Return the maximum distance between two houses with different colors.
Example:
Input: colors = [1, 1, 2, 3, 1, 2]
Output: 5
Explanation: The furthest two houses with different colors are house 0 (color 1) and house 5 (color 2), which are 5 units apart.
colors
can range from 2 to 100.public class FurthestHouses {
public int maxDistance(int[] colors) {
int n = colors.length;
int maxDistance = 0;
// Check distance from the first house
for (int i = n - 1; i >= 0; i--) {
if (colors[i] != colors[0]) {
maxDistance = Math.max(maxDistance, i);
break;
}
}
// Check distance from the last house
for (int i = 0; i < n; i++) {
if (colors[i] != colors[n - 1]) {
maxDistance = Math.max(maxDistance, n - 1 - i);
break;
}
}
return maxDistance;
}
public static void main(String[] args) {
FurthestHouses fh = new FurthestHouses();
int[] colors = {1, 1, 2, 3, 1, 2};
System.out.println(fh.maxDistance(colors)); // Output: 5
}
}
n
is the length of the array colors
.By following this strategy, we ensure that we cover all edge cases and obtain the correct maximum distance efficiently.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?