Two Furthest Houses With Different Colors

easy greedy array two pointers

Problem

There are n houses in a row, painted with colors given by a 0-indexed array colors. Return the maximum distance between two houses with different colors, where the distance between houses i and j is abs(i - j).

Inputcolors = [1,1,1,6,1,1,1]
Output3
House 0 (color 1) and house 3 (color 6) differ; distance abs(0 - 3) = 3. Houses 3 and 6 also give 3.
Inputcolors = [1,8,3,8,3]
Output4
House 0 (color 1) and house 4 (color 3) differ; distance abs(0 - 4) = 4.

def maxDistance(colors):
    n = len(colors)
    best = 0
    for i in range(n):
        if colors[i] != colors[0]:
            best = max(best, i)
        if colors[i] != colors[n - 1]:
            best = max(best, n - 1 - i)
    return best
function maxDistance(colors) {
  const n = colors.length;
  let best = 0;
  for (let i = 0; i < n; i++) {
    if (colors[i] !== colors[0])
      best = Math.max(best, i);
    if (colors[i] !== colors[n - 1])
      best = Math.max(best, n - 1 - i);
  }
  return best;
}
int maxDistance(int[] colors) {
    int n = colors.length;
    int best = 0;
    for (int i = 0; i < n; i++) {
        if (colors[i] != colors[0])
            best = Math.max(best, i);
        if (colors[i] != colors[n - 1])
            best = Math.max(best, n - 1 - i);
    }
    return best;
}
int maxDistance(vector<int>& colors) {
    int n = colors.size();
    int best = 0;
    for (int i = 0; i < n; i++) {
        if (colors[i] != colors[0])
            best = max(best, i);
        if (colors[i] != colors[n - 1])
            best = max(best, n - 1 - i);
    }
    return best;
}
Time: O(n) Space: O(1)