Search⌘ K
AI Features

Solution: Help the Police Officers Catch the Thieves

Explore how a greedy algorithm can optimize matching police officers to thieves, improving time complexity from O(n²) with brute force to O(n). Learn to implement this efficient approach in Java for coding interviews.

Solution #1: Brute force

Java
class MaxThief {
public static int policeThief(char[] policeThiefArray, int n, int k) {
int result = 0;
boolean[] caught = new boolean[n];
for (int i = 0; i < n; i++) {
caught[i] = false;
}
for (int i = 0; i < n; i++) {
//check k steps forward
if (policeThiefArray[i] == 'P' && caught[i] == false) {
for (int j = i; j < (j + k) && j < n ; j++) {
if (policeThiefArray[j] == 'T' && caught[j] == false) {
caught[i] = true;
caught[j] = true;
result++;
break;
}
}
}
//check k steps backward
if (policeThiefArray[i] == 'P' && caught[i] == false) {
for (int j = i; j > (j - k) && j > -1 ; j--) {
if (policeThiefArray[j] == 'T' && caught[j] == false) {
caught[i] = true;
caught[j] = true;
result++;
break;
}
}
}
}
return result;
}
}
class Main{
public static void main(String[] args) {
int k, n;
char policeTheifArray[] = {'P', 'T', 'T', 'P', 'T'};
k = 2;
n = policeTheifArray.length;
System.out.println("Maximum thieves caught for {P, T, T, P, T}: " + MaxThief.policeThief(policeTheifArray, n, k));
char policeTheifArray1[] = {'T', 'T', 'P', 'P', 'T', 'P'};
k = 2;
n = policeTheifArray1.length;
System.out.println("Maximum thieves caught for {T, T, P, P, T,P}: " + MaxThief.policeThief(policeTheifArray1, n, k));
}
}

Explanation

The brute force method takes the first police found and tries to match it with the nearest thief. However, you can see that this method is very lengthy, confusing, and time-intensive.

Time complexity

The time complexity is O(nk)O(nk). There are two for loops (one for kk forward steps and one for kk ...