-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path2078.py
95 lines (80 loc) · 2.74 KB
/
2078.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
# [ LeetCode ] 2078. Two Furthest Houses With Different Colors
def solution(colors: list[int]) -> int:
colors_indexes: dict[int, list[int]] = {}
for idx, color in enumerate(colors):
if color in colors_indexes:
colors_indexes[color][1] = idx
else:
colors_indexes[color] = [idx, idx]
from_first: list[list[int]] = sorted(
colors_indexes.values(), key=lambda x: x[0]
)
from_last: list[list[int]] = sorted(
colors_indexes.values(), key=lambda x: x[1], reverse=True
)
if from_first[0] == from_last[0]:
return max(
from_last[0][1] - from_first[1][0],
from_last[1][1] - from_first[0][0]
)
else:
return from_last[0][1] - from_first[0][0]
def another_solution(colors: list[int]) -> int:
def find_different_color(
target: int, start: int, last: int, reverse: int
) -> int:
for idx in range(start, last, reverse):
if colors[idx] != target:
return idx
return -1
length: int = len(colors)
if colors[0] == colors[-1]:
middle: int = length // 2
from_left: int = find_different_color(
target=colors[0], start=0, last=middle, reverse=1
)
from_right: int = find_different_color(
target=colors[0], start=length-1, last=middle-1, reverse=-1
)
if from_left == -1:
return from_right
elif from_right == -1:
return length - 1 - from_left
else:
return max(length - 1 - from_left, from_right)
else:
return length - 1
def simple_solution(colors: list[int]) -> int:
answer: int = 0
first_color, last_color = colors[0], colors[-1]
for idx, color in enumerate(colors):
if color != first_color:
answer = max(answer, idx)
if color != last_color:
answer = max(answer, len(colors) - 1 - idx)
return answer
if __name__ == "__main__":
cases: list[dict[str, dict[str, list[int]] | int]] = [
{
"input": { "colors": [1, 1, 1, 6, 1, 1, 1] },
"output": 3
},
{
"input": { "colors": [1, 8, 3, 8, 3] },
"output": 4
},
{
"input": { "colors": [0, 1] },
"output": 1
},
{
"input": {
"colors": [4, 4, 4, 11, 4, 4, 11, 4, 4, 4, 4, 4]
},
"output": 8
}
]
for case in cases:
assert case["output"] == solution(**case["input"])
assert case["output"] == another_solution(**case["input"])
assert case["output"] == simple_solution(**case["input"])