Two Furthest Houses With Different Colors — LeetCode 2078 Python Solution
- Problem
- #2078
- Pattern
- Greedy
- Reading time
- 2 min
- Source
- leetcode.com
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
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 ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n log n) |
| Space | O(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.