Implement the Greedy Algorithm discussed for the problem below, in C++. Using C++, implement the given problem below. (Greedy Algorithm) 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: Input arr[] = {'P', 'T', 'T', 'P', 'T'}, k = 1. Output: 2. Here maximum 2 thieves can be caught, first policeman catches first thief and second police- man can catch either second or third thief. Input = arr[] = {'T', 'T', 'P', 'P', 'T', 'P'}, k = 2. Output: 3. Input arr[] = {'P', 'T', 'P', 'T', 'T', 'P'}, k = 3. Output: 3.
Implement the Greedy
C++.
Using C++, implement the given problem below. (Greedy Algorithm)
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:
Input arr[] = {'P', 'T', 'T', 'P', 'T'}, k = 1.
Output: 2.
Here maximum 2 thieves can be caught, first policeman catches first thief and second police- man can catch either second or third thief.
Input = arr[] = {'T', 'T', 'P', 'P', 'T', 'P'}, k = 2.
Output: 3.
Input arr[] = {'P', 'T', 'P', 'T', 'T', 'P'}, k = 3.
Output: 3.
Copy the code. Show the algorithm use. Don't copy code from other sites.
Trending now
This is a popular solution!
Step by step
Solved in 3 steps with 5 images