Skip to content

Commit bf841d6

Browse files
committed
Add: Maximize Distance to Closest Person
1 parent 2b913c1 commit bf841d6

File tree

2 files changed

+58
-0
lines changed

2 files changed

+58
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -1 +1,28 @@
11
package maximize_distance_to_closest_person
2+
3+
func maxDistToClosest(seats []int) int {
4+
ans, prev, future, l := 0, -1, 0, len(seats)
5+
for i, v := range seats {
6+
if v == 1 {
7+
prev = i
8+
} else {
9+
for future < l && seats[future] == 0 || future < i {
10+
future++
11+
}
12+
left, right := l, l
13+
if prev != -1 {
14+
left = i - prev
15+
}
16+
if future != l {
17+
right = future - i
18+
}
19+
if right < left {
20+
left = right
21+
}
22+
if left > ans {
23+
ans = left
24+
}
25+
}
26+
}
27+
return ans
28+
}
Original file line numberDiff line numberDiff line change
@@ -1 +1,32 @@
11
package maximize_distance_to_closest_person
2+
3+
import "testing"
4+
5+
type caseType struct {
6+
input []int
7+
expected int
8+
}
9+
10+
func TestMaxDistToClosest(t *testing.T) {
11+
tests := [...]caseType{
12+
{
13+
input: []int{1, 0, 0, 0, 1, 0, 1},
14+
expected: 2,
15+
},
16+
{
17+
input: []int{1, 0, 0, 0},
18+
expected: 3,
19+
},
20+
21+
{
22+
input: []int{0, 0, 0, 1},
23+
expected: 3,
24+
},
25+
}
26+
for _, tc := range tests {
27+
output := maxDistToClosest(tc.input)
28+
if output != tc.expected {
29+
t.Fatalf("input: %v, output: %v, expected: %v", tc.input, output, tc.expected)
30+
}
31+
}
32+
}

0 commit comments

Comments
 (0)