Two Furthest Houses With Different Colors — LeetCode 2078 Python Solution

EasyGreedyArray
Problem
#2078
Pattern
Greedy
Reading time
2 min

The problem

There are n houses evenly lined up on the street, and each house is beautifully painted. You are given a 0-indexed integer array colors of length n, where colors[i] represents the color of the ith house.

Example

Input
colors = [1,1,1,6,1,1,1]
Output
3
Explanation
In the above image, color 1 is blue, and color 6 is red.

Python solution

Python
class Solution:
    def maxDistance(self, colors: List[int]) -> int:
        ans, n = 0, len(colors)
        for i in range(n):
            for j in range(i + 1, n):
                if colors[i] != colors[j]:
                    ans = max(ans, abs(i - j))
        return ans

Complexity

MeasureComplexity
TimeO(n log n)
SpaceO(1) to O(n) auxiliary

Pattern: Greedy

Take the locally best option every time — when you can prove that never costs you later. LeetCode 2078. Two Furthest Houses With Different Colors is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Greedy.

The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2078. Two Furthest Houses With Different Colors?
LeetCode 2078. Two Furthest Houses With Different Colors is rated Easy on LeetCode.
What topics does LeetCode 2078. Two Furthest Houses With Different Colors cover?
LeetCode 2078. Two Furthest Houses With Different Colors is tagged Greedy and Array on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview