![]() |
VOOZH | about |
Given an array arr[], where each element represents either a policeman (P) or a thief (T). Each policeman can catch only one thief and policeman can only catch a thief if the distance between them is at most k units. Find the maximum number of thieves that can be caught.
Examples:
Input: arr[] = ['P', 'T', 'T', 'P', 'T'], k = 1
Output: 2.
Explanation: policeman of 0th index catches thief at index 1 and policeman of 3rd index can catch thief at either 2nd or 4th index.
Input: arr[] = ['T', 'T', 'P'], k = 1
Output: 1
Explanation: Policeman of 2th index catches thief at index 1.
Table of Content
The idea is that for every policeman, we search for a thief within a range of 2*k + 1 in a sequential manner. If a thief is found, we mark index into the caught array to ensure that the same thief is not caught multiple times.
2
The idea is to maintain two queues for police and thief indices. Traverse the array, enqueue positions, and match from the front if the distance ≤ k. Dequeue accordingly to count maximum catches.
Working:
Traverse the array and enqueue the index of each police officer or thief into their respective queues. Then, repeatedly compare the front elements of both queues. If the distance between the police and the thief at the front is less than or equal to k, we catch the thief and dequeue both. If the police index is smaller, it means this policeman cannot catch the thief at the front, so we dequeue the police. Otherwise, if the thief is too far left, we dequeue the thief.
2
The idea is to use two pointers (both begin from left side): one to keep track of policemen and the other for thieves. We traverse the array while maintaining these pointers. If a policeman and a thief are within the allowed range k, the thief is caught, and both pointers move forward. If the thief is too far left, we move the thief pointer forward otherwise policeman is too far left, we move the policeman pointer forward.
2