Problem Description
Given an array where each element represents the color of a house aligned in a row, determine the maximum distance (absolute difference of indices) between two houses that have different colors.
Key Insights
- The maximum possible distance is between the first and last house in the array.
- If the first and last house are painted in different colors, the answer is simply the length of the array minus one.
- If they are the same, search inward from both ends to locate the furthest house with a different color.
- Since there is a guarantee that at least two houses are painted differently, one of these checks will always provide the maximum distance.
Space and Time Complexity
Time Complexity: O(n) because we are scanning the array at most twice. Space Complexity: O(1) since only a few extra variables are used.
Solution
The solution first checks the two end houses. If their colors are different, the maximum distance is the array length minus one. If they are the same, the solution performs two passes: one starting from the right side to find the first house with a different color from the first house, and one starting from the left side to find the first house with a different color from the last house. The maximum of these two distances is returned. This approach avoids checking every possible pair and guarantees optimal performance.