Two Furthest Houses With Different Colors

There are n houses evenly lined up on a street, and each house is painted. You are given a 0-indexed integer array colors of length n, where colors[i] is the color of the ith house. Return the maximum distance between two houses with different colors. The distance between the ith and jth houses is abs(i - j).

30:00

Two Furthest Houses With Different Colors
easy
Free written solution
Topics
Companies

There are n houses evenly lined up on a street, and each house is painted. You are given a 0-indexed integer array colors of length n, where colors[i] is the color of the ith house. Return the maximum distance between two houses with different colors. The distance between the ith and jth houses is abs(i - j).

Example 1:
Input: {"colors":[1,1,1,6,1,1,1]}
Output: 3
Constraints:
  • n==colors.lengthn == \text{colors.length}

  • 2≤n≤1002 \leq n \leq 100

  • 0≤colors[i]≤1000 \leq \text{colors}[i] \leq 100

  • Test data are generated such that at least two houses have different colors.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"colors":[1,1,1,6,1,1,1]}

7 houses. The widest pair with different colors must use house 0 or house 6: if neither end were in it, swapping in an end would only widen it.

the street

1

0

1

1

1

2

6

3

1

4

1

5

1

6

house 0 ↔ furthest different

-

furthest different ↔ last house

-

Variables
VariableValue
n7
right-1
left-1
DepthFunction Call
Stack empty
0/17