/**
* Problem: LeetCode 2078 - Two Furthest Houses With Different Colors
* Difficulty: Easy
* Language: Java
* Author: CodeByTushu
*/
class Solution {
public int maxDistance(int[] colors) {
final int n = colors.length;
int maxDist = 0;
// The furthest house with a different color must pair with either the first or last house
for (int i = 0; i < n; ++i) {
if (colors[i] != colors[0]) {
maxDist = Math.max(maxDist, i);
}
if (colors[i] != colors[n - 1]) {
maxDist = Math.max(maxDist, n - 1 - i);
}
}
return maxDist;
}
}
"""
Problem: LeetCode 2078 - Two Furthest Houses With Different Colors
Difficulty: Easy
Language: Python
Author: CodeByTushu
"""
from typing import List
class Solution:
def maxDistance(self, colors: List[int]) -> int:
n = len(colors)
max_dist = 0
# The furthest house with a different color must pair with either the first or last house
for i, c in enumerate(colors):
if c != colors[0]:
max_dist = max(max_dist, i)
if c != colors[-1]:
max_dist = max(max_dist, n - 1 - i)
return max_dist
/**
* Problem: LeetCode 2078 - Two Furthest Houses With Different Colors
* Difficulty: Easy
* Language: C++
* Author: CodeByTushu
*/
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
int maxDistance(vector<int>& colors) {
const int n = colors.size();
int maxDist = 0;
// The furthest house with a different color must pair with either the first or last house
for (int i = 0; i < n; ++i) {
if (colors[i] != colors[0]) {
maxDist = max(maxDist, i);
}
if (colors[i] != colors[n - 1]) {
maxDist = max(maxDist, n - 1 - i);
}
}
return maxDist;
}
};
/**
* Problem: LeetCode 2078 - Two Furthest Houses With Different Colors
* Difficulty: Easy
* Language: JavaScript
* Author: CodeByTushu
*/
/**
* @param {number[]} colors
* @return {number}
*/
var maxDistance = function(colors) {
const n = colors.length;
let maxDist = 0;
// The furthest house with a different color must pair with either the first or last house
for (let i = 0; i < n; ++i) {
if (colors[i] !== colors[0]) {
if (i > maxDist) maxDist = i;
}
if (colors[i] !== colors[n - 1]) {
const d = n - 1 - i;
if (d > maxDist) maxDist = d;
}
}
return maxDist;
};