# Policemen catch thieves in C++

C++Server Side ProgrammingProgramming

In this problem, we are given an array of n elements. Each element of the array has either a policeman or a thief, one thief can be caught by one police and we have to find the maximum number of thieves that can be caught by the police if a policeman can catch a thief k units away from him.

Let’s take an example to understand the problem,

Input

array = {T, P, P, P, T , T, T}
K = 2.

Output − 3

Explanation − here, each policeman will catch a thief,

P at index 1 will catch T at index 0.
P at index 2 will catch T at index 4.
P at index 3 will catch T at index 5.

This is allowed as policemen can catch thieves who are at distance 2 away from them.

To solve this problem, we will use the greedy algorithm. It can work in two ways, either catch all thieves nearest to a policeman or catch thieves farthest to the policeman. But in both case, the most optimum solution is not found as both lags are some case where a policeman has to catch a thieve at a certain distance from him.

So, the following is an algorithm that provides the most promising results,

We will start with the indexes of the first policeman and thief. If |index(P1) - index(T1)| <= k, the thief can be caught and we will check for the next police-thief pair. Otherwise, we will increase min(p,t) and check for the next index of police and thief. This check is to be done until all policemen and thieves are checked and in the end the number of thieves caught is printed.

## Example

Program to show the illustration of our algorithm,

Live Demo

#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int policeThief(char arr[], int n, int k){
int caught = 0;
vector<int> thieves;
vector<int> policemen;
for (int i = 0; i < n; i++) {
if (arr[i] == 'P')
policemen.push_back(i);
else if (arr[i] == 'T')
thieves.push_back(i);
}
int thief = 0, police = 0;
while (thief < thieves.size() && police < policemen.size()) {
if (abs(thieves[thief] - policemen[police]) <= k) {
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);
cout << "Maximum number of thieves that can be caught by police is :"<<policeThief(arr2, n, k);
return 0;
}

## Output

Maximum number of thieves that can be caught by police is :4