Leetcode 2511. Maximum Enemy Forts That Can Be Captured
You are given a 0-indexed array forts
of length n
representing positions on a line, where:
-1
represents an enemy fort,0
represents an empty position,1
represents your fort.You want to capture enemy forts. You can only capture an enemy fort if you have your fort to the left and right side of the enemy fort and there are empty positions between your fort and the enemy fort.
Return the maximum number of enemy forts that can be captured.
0
if no enemy fort can be captured.0
since the conditions of having your fort on both sides cannot be met.1
).public class MaxEnemyFortsCaptured {
public int captureForts(int[] forts) {
int maxCaptured = 0, n = forts.length;
for (int i = 0; i < n; i++) {
if (forts[i] == 1) {
// Search to the right
int rightCount = 0;
for (int j = i + 1; j < n; j++) {
if (forts[j] == 0) {
rightCount++;
} else if (forts[j] == -1) {
maxCaptured = Math.max(maxCaptured, rightCount);
break;
} else {
break;
}
}
// Search to the left
int leftCount = 0;
for (int j = i - 1; j >= 0; j--) {
if (forts[j] == 0) {
leftCount++;
} else if (forts[j] == -1) {
maxCaptured = Math.max(maxCaptured, leftCount);
break;
} else {
break;
}
}
}
}
return maxCaptured;
}
public static void main(String[] args) {
MaxEnemyFortsCaptured solution = new MaxEnemyFortsCaptured();
int[] forts = {1, 0, 0, -1, 0, 1, 0, -1, 0, 1};
System.out.println(solution.captureForts(forts)); // Output should be the maximum number of enemy forts that can be captured
}
}
forts
array.1
, we search both left and right. Each search is (O(n)) in the worst case. Since we only do this for entries with your fort (1
), it would typically be (O(n)) across the entire array.In the worst-case scenario, both traversals together result in (O(n^2)).
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?