LeetCode 2078. Two Furthest Houses With Different Colors
考点 | 难度 |
---|---|
Greedy | Easy |
题目
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.
Return the maximum distance between two houses with different colors.
The distance between the ith and jth houses is abs(i - j)
, where abs(x)
is the absolute value of x.
思路
固定最左边的房子,从最右边的房子向左移动直到找到不同,再固定最右边的房子,从最左边的向右移动。比较两个数字的大小,返回大的一个。
leetcode的hint2: Greedily, the maximum distance will come from either the pair of the leftmost house and possibly some house on the right with a different color, or the pair of the rightmost house and possibly some house on the left with a different color.
答案
public int maxDistance(int[] colors) {
int size = colors.length - 1;
int half = colors.length / 2;
for(int i = 0; i <= half; i++) {
if((colors[size] != colors[i]) || colors[0] != colors[size - i]) {
return size - i;
}
}
return -1;
}