Two Furthest Houses With Different Colors

  1. Identify the color of the first house.
  2. Find the first position ( p ) where a different color appears.
  3. Iterate through the remaining colors to find the maximum distance using the rules you provided.

Here’s the updated code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution:
    def maxDistance(self, colors: List[int]) -> int:
        first_color = colors[0]
        # Find the first position (p) where a different color appears
        p = 0
        for i in range(1, len(colors)):
            if colors[i] != first_color:
                p = i
                break

        # Initialize the maximum distance
        max_distance = p

        # Iterate through the remaining colors to find the maximum distance
        for i in range(p + 1, len(colors)):
            if colors[i] != first_color:
                max_distance = i
            else:
                max_distance = max(max_distance, i - p)

        return max_distance

Example

For the input colors = [0,1], the method would now return 1, since the first color is 0, and the first different color appears at position 1. Therefore, the maximum distance is 1.