Find Latest Group of Size M LeetCode solution in Python

1
class Solution:
2
def findLatestStep(self, arr: List[int], m: int) -> int:
3
n = len(arr)
4
ans = -1
5
if n == m:
6
return m # just in case
7

8
# make in "inverted" array with artificial ends higher then everything between
9

10
sor = [0 for _ in range(n + 2)]
11
for i in range(n):
12
sor[(arr[i])] = i + 1
13
sor[0] = sor[n + 1] = n + 1
14

15
# scan and see, if ones in the middle of space of length m appear
16
# before ones on its ends,
17
# and find the latest of such spaces to disappear, if exists
18

19
for i in range(1, n - m + 2):
20
if all(
21
sor[i - 1] > sor[j] and sor[i + m] > sor[j] for j in range(i, i + m)
22
):
23
if min(sor[i - 1] - 1, sor[i + m] - 1) > ans:
24
ans = min(sor[i - 1] - 1, sor[i + m] - 1)
25
return ans

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0