Leetcode 2511. Maximum Enemy Forts That Can Be Captured
You are given a 0-indexed integer array forts
of length n
representing the positions of fortifications along a line, where:
1
represents your fort.-1
represents an enemy fort.0
represents an empty position.You want to capture all enemy forts by sending your army from one of your forts to an enemy fort through empty positions. Your army can only capture enemy forts that are directly reachable from one of your forts without passing through any other fort. More formally, you can only capture an enemy fort k
if you can find an integer i
such that:
forts[i] == 1
forts[k] == -1
forts[i+1], forts[i+2], ..., forts[k-1]
are 0
.Return the maximum number of enemy forts that can be captured.
1
) or enemy (-1
) forts?
forts
?
1
or -1
in the array?
1
or -1
.1
(friendly fort), look for the nearest -1
(enemy fort) to both its left and right sides.0
). If they are, calculate the distance between the two and keep track of the maximum captured forts.#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
int captureForts(vector<int>& forts) {
int n = forts.size();
int maxCaptured = 0;
for (int i = 0; i < n; ++i) {
if (forts[i] == 1) {
// Check right side
int j = i + 1;
while (j < n && forts[j] == 0) {
++j;
}
if (j < n && forts[j] == -1) {
maxCaptured = max(maxCaptured, j - i - 1);
}
// Check left side
j = i - 1;
while (j >= 0 && forts[j] == 0) {
--j;
}
if (j >= 0 && forts[j] == -1) {
maxCaptured = max(maxCaptured, i - j - 1);
}
}
}
return maxCaptured;
}
};
maxCaptured
to 0 to keep track of the maximum number of enemy forts that can be captured.1
, then:
j
), and check if all elements up to the next non-zero are 0
and if it ends in -1
(enemy fort). Update maxCaptured
.j
), and check similarly.maxCaptured
as the result.This strategy ensures that we find the maximum reachable enemy fort directly from any friendly fort by traversing only once through the array.
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?