#2078

Two Furthest Houses With Different Colors

Easy
LeetCode ↗

Approaches

💡

Intuition

Time O(n²)Space O(1)

The brute-force approach checks every possible pair of houses to find the maximum distance between two houses of different colors. This is straightforward but inefficient for larger inputs.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a variable to keep track of the maximum distance found.
  2. 2Step 2: Use two nested loops to iterate through all pairs of houses.
  3. 3Step 3: For each pair, check if the colors are different. If they are, calculate the distance and update the maximum distance if this distance is greater.
solution.py8 lines
1def maxDistance(colors):
2    max_dist = 0
3    n = len(colors)
4    for i in range(n):
5        for j in range(i + 1, n):
6            if colors[i] != colors[j]:
7                max_dist = max(max_dist, j - i)
8    return max_dist

Complexity note: The time complexity is O(n²) because we are using two nested loops to check every pair of houses. The space complexity is O(1) as we are using a constant amount of space.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.