...

/

Solution: Help the Police Officers Catch the Thieves

Solution: Help the Police Officers Catch the Thieves

This review provides a detailed analysis of the solution to the catching thieves problem.

Solution #1: Brute force

Press + to interact
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 ...

Access this course and 1400+ top-rated courses and projects.