-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpolicemen-catch-thieves.py
52 lines (44 loc) · 1.17 KB
/
policemen-catch-thieves.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
# Python program to find maximum number of thieves caught
# Returns maximum number of thieves that can be caught.
def policeThief(arr, n, k):
i = 0
l = 0
r = 0
res = 0
thi = []
pol = []
# store indices in list
while i < n:
if arr[i] == 'P':
pol.append(i)
elif arr[i] == 'T':
thi.append(i)
i += 1
# track lowest current indices of
# thief: thi[l], police: pol[r]
while l < len(thi) and r < len(pol):
# can be caught
if (abs( thi[l] - pol[r] ) <= k):
res += 1
l += 1
r += 1
# increment the minimum index
elif thi[l] < pol[r]:
l += 1
else:
r += 1
return res
# Driver program
arr1 = ['P', 'T', 'T', 'P', 'T']
k = 2
n = len(arr1)
print("Maximum thieves caught: {}".format(policeThief(arr1, n, k)))
arr2 = ['T', 'T', 'P', 'P', 'T', 'P']
k = 2
n = len(arr2)
print("Maximum thieves caught: {}".format(policeThief(arr2, n, k)))
arr3 = ['P', 'T', 'P', 'T', 'T', 'P']
k = 3
n = len(arr3)
print("Maximum thieves caught: {}".format(policeThief(arr3, n, k)))
# This code is contributed by `jahid_nadim`