You are given a 0-indexed integer array forts of length n representing the positions of several forts. forts[i] can be -1, 0, or 1 where:
-1 represents there is no fort at the ith position.
0 indicates there is an enemy fort at the ith position.
1 indicates the fort at the ith the position is under your command.
Now you have decided to move your army from one of your forts at position i
to an empty position j such that:
0 <= i, j <= n - 1
The army travels over enemy forts only. Formally, for all k where min(i,j) < k < max(i,j), forts[k] == 0.
While moving the army, all the enemy forts that come in the way are
captured.
Return themaximum number of enemy forts that can be captured. In case it is impossible to move your army, or you do not have any fort under your command, return 0.
Input: forts =[1,0,0,-1,0,0,0,0,1]Output: 4Explanation:
- Moving the army from position 0 to position 3 captures 2 enemy forts, at 1 and 2.- Moving the army from position 8 to position 3 captures 4 enemy forts.Since 4is the maximum number of enemy forts that can be captured, we return4.
We want to find the longest segment of consecutive enemy forts (0s) between two of your forts (1 and -1, or -1 and 1). We can scan the array and, whenever we see a 1 or -1, look for the next occurrence of the opposite fort, counting the zeros in between.
classSolution {
public:int captureForts(vector<int>& forts) {
int ans =0, prev =-1, n = forts.size();
for (int i =0; i < n; ++i) {
if (forts[i] !=0) {
if (prev !=-1&& forts[i] != forts[prev]) {
ans = max(ans, abs(i - prev) -1);
}
prev = i;
}
}
return ans;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
funccaptureForts(forts []int) int {
ans, prev:=0, -1fori, v:=rangeforts {
ifv!=0 {
ifprev!=-1&&v!=forts[prev] {
ifi-prev-1 > ans {
ans = i-prev-1 }
}
prev = i }
}
returnans}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
classSolution {
publicintcaptureForts(int[] forts) {
int ans = 0, prev =-1;
for (int i = 0; i < forts.length; i++) {
if (forts[i]!= 0) {
if (prev !=-1 && forts[i]!= forts[prev]) {
ans = Math.max(ans, Math.abs(i - prev) - 1);
}
prev = i;
}
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
classSolution {
funcaptureForts(forts: IntArray): Int {
var ans = 0var prev = -1for (i in forts.indices) {
if (forts[i] !=0) {
if (prev != -1&& forts[i] != forts[prev]) {
ans = maxOf(ans, kotlin.math.abs(i - prev) - 1)
}
prev = i
}
}
return ans
}
}
1
2
3
4
5
6
7
8
9
10
classSolution:
defcaptureForts(self, forts: list[int]) -> int:
ans =0 prev =-1for i, v in enumerate(forts):
if v !=0:
if prev !=-1and v != forts[prev]:
ans = max(ans, abs(i - prev) -1)
prev = i
return ans
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
impl Solution {
pubfncapture_forts(forts: Vec<i32>) -> i32 {
letmut ans =0;
letmut prev =-1;
for (i, &v) in forts.iter().enumerate() {
if v !=0 {
if prev !=-1&& v != forts[prev asusize] {
ans = ans.max((i asi32- prev -1).abs());
}
prev = i asi32;
}
}
ans
}
}