Skip to content

Commit 039ad55

Browse files
authored
Merge pull request #75 from sahil2128/master
New Problem Statement
2 parents 214077d + 80c5fcc commit 039ad55

File tree

2 files changed

+87
-0
lines changed

2 files changed

+87
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
# Policemen catch thieves
2+
3+
Given an array of size n that has the following specifications:
4+
5+
Each element in the array contains either a policeman or a thief.
6+
Each policeman can catch only one thief.
7+
A policeman cannot catch a thief who is more than K units away from the policeman.
8+
We need to find the maximum number of thieves that can be caught.
9+
Examples:
10+
11+
```bash
12+
Input : arr[] = {'P', 'T', 'T', 'P', 'T'},
13+
k = 1.
14+
Output : 2.
15+
```
16+
Here maximum 2 thieves can be caught, first
17+
policeman catches first thief and second police-
18+
man can catch either second or third thief.
19+
20+
```
21+
Input : arr[] = {'T', 'T', 'P', 'P', 'T', 'P'},
22+
k = 2.
23+
Output : 3.
24+
```
25+
```
26+
Input : arr[] = {'P', 'T', 'P', 'T', 'T', 'P'},
27+
k = 3.
28+
Output : 3.
29+
```
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
# Python3 program to find maximum
2+
# number of thieves caught
3+
4+
# Returns maximum number of thieves
5+
# that can be caught.
6+
def policeThief(arr, n, k):
7+
i = 0
8+
l = 0
9+
r = 0
10+
res = 0
11+
thi = []
12+
pol = []
13+
14+
# store indices in list
15+
while i < n:
16+
if arr[i] == 'P':
17+
pol.append(i)
18+
elif arr[i] == 'T':
19+
thi.append(i)
20+
i += 1
21+
22+
# track lowest current indices of
23+
# thief: thi[l], police: pol[r]
24+
while l < len(thi) and r < len(pol):
25+
26+
# can be caught
27+
if (abs( thi[l] - pol[r] ) <= k):
28+
res += 1
29+
l += 1
30+
r += 1
31+
32+
# increment the minimum index
33+
elif thi[l] < pol[r]:
34+
l += 1
35+
else:
36+
r += 1
37+
38+
return res
39+
40+
# Driver program
41+
if __name__=='__main__':
42+
arr1 = ['P', 'T', 'T', 'P', 'T']
43+
k = 2
44+
n = len(arr1)
45+
print(("Maximum thieves caught: {}".
46+
format(policeThief(arr1, n, k))))
47+
48+
arr2 = ['T', 'T', 'P', 'P', 'T', 'P']
49+
k = 2
50+
n = len(arr2)
51+
print(("Maximum thieves caught: {}".
52+
format(policeThief(arr2, n, k))))
53+
54+
arr3 = ['P', 'T', 'P', 'T', 'T', 'P']
55+
k = 3
56+
n = len(arr3)
57+
print(("Maximum thieves caught: {}".
58+
format(policeThief(arr3, n, k))))

0 commit comments

Comments
 (0)