Two Furthest Houses With Different Colors - Problem
Two Furthest Houses With Different Colors
Imagine walking down a beautiful street lined with n colorfully painted houses. Each house has been painted with a specific color, and you want to find the maximum distance between any two houses that have different colors.
You are given a
Goal: Return the maximum distance between two houses with different colors.
The distance between the
Example: If we have houses with colors
Imagine walking down a beautiful street lined with n colorfully painted houses. Each house has been painted with a specific color, and you want to find the maximum distance between any two houses that have different colors.
You are given a
0-indexed integer array colors of length n, where colors[i] represents the color of the i-th house.Goal: Return the maximum distance between two houses with different colors.
The distance between the
i-th and j-th houses is abs(i - j), where abs(x) is the absolute value of x.Example: If we have houses with colors
[1, 1, 1, 6, 1, 1, 1], the maximum distance would be between house 0 (color 1) and house 3 (color 6), giving us a distance of abs(0 - 3) = 3. Input & Output
example_1.py โ Basic Case
$
Input:
[1,1,1,6,1,1,1]
โบ
Output:
3
๐ก Note:
The houses at indices 0 and 3 have different colors (1 and 6). The distance is abs(0 - 3) = 3. This is the maximum distance possible.
example_2.py โ Multiple Colors
$
Input:
[1,8,3,8,3]
โบ
Output:
4
๐ก Note:
The houses at indices 0 and 4 have different colors (1 and 3). The distance is abs(0 - 4) = 4. This gives us the maximum distance.
example_3.py โ Alternating Colors
$
Input:
[0,1]
โบ
Output:
1
๐ก Note:
The houses at indices 0 and 1 have different colors (0 and 1). The distance is abs(0 - 1) = 1.
Constraints
- 2 โค n โค 100
- 0 โค colors[i] โค 100
- At least two houses have different colors
Visualization
Tap to expand
Understanding the Visualization
1
Survey the Street
Look at all the colorfully painted houses lined up
2
Key Insight
The maximum distance must include either the first or last house
3
Check Both Ends
Find the furthest different colored house from each end
4
Take the Best Shot
Choose the maximum distance for the most dramatic photo
Key Takeaway
๐ฏ Key Insight: The maximum distance between houses with different colors must always include either the first house (leftmost) or the last house (rightmost) as one of the endpoints. This allows us to solve the problem efficiently in O(n) time!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code