Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions Police catch thieves/Police_catch_thieves.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
#include <iostream>
#include <bits/stdc++.h>
using namespace std;

//returning maximum number of thieves that can be caught
int policeThief(char arr[], int n, int k){
int caught = 0;
vector<int> thieves;
vector<int> policemen;
for (int i = 0; i < n; i++) { // here we are stroing indices in the vectors
if (arr[i] == 'P')
policemen.push_back(i);
else if (arr[i] == 'T')
thieves.push_back(i);
}
int thief = 0, police = 0; // tracking the lower indices
while (thief < thieves.size() && police < policemen.size()) {
if (abs(thieves[thief] - policemen[police]) <= k) { // thieves that can be caught
caught++;
thief++;
police++;
}
else if (thieves[thief] < policemen[police])
thief++;
else
police++;
}
return caught;
}
int main(){
int k, n;
char arr2[] = {'P', 'T', 'T', 'P', 'P', 'T', 'T', 'T', 'T', 'P' };
k = 2;
n = sizeof(arr2) / sizeof(arr2[0]);
cout << "Maximum number of thieves that can be caught by police is :"<<policeThief(arr2, n, k);
return 0;
}
36 changes: 36 additions & 0 deletions Police catch thieves/Readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
# POLICEMEN CATCH THIEVES

Given an array of size n that has the following specifications:

1-Each element in the array contains either a policeman or a thief.

2-Each policeman can catch only one thief.

3-A policeman cannot catch a thief who is more than K units away from the policeman.

We need to find the maximum number of thieves that can be caught.
Examples:
## Running Tests

### Input

```bash
arr[] = {'P', 'T', 'T', 'P', 'T'},
k = 1.
```
### Output

```bash
2
```

### Input
```bash
arr[] = {'T', 'T', 'P', 'P', 'T', 'P'},
k = 2
```

### Output
```bash
3
```