Skip to main content
Back to problems
#2511
Easy Algorithms

Maximum enemy forts that can be captured

Array Two Pointers
41.1% acceptance
Feb 25, 2026
326
304
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 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 the maximum 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.

Solution

Rust
Time O(n²)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn capture_forts(forts: Vec<i32>) -> i32 {
    let n = forts.len();
    let mut ans = 0;
    let mut i = 0;
    while i < n {
      if forts[i] == 1 || forts[i] == -1 {
        let start = forts[i];
        let mut j = i + 1;
        while j < n && forts[j] == 0 {
          j += 1;
        }
        if j < n && forts[j] == -start {
          ans = ans.max((j - i - 1) as i32);
        }
        i = j;
      } else {
        i += 1;
      }
    }
    ans
  }
}